有没有办法使用jsonpath-ng从JSON提取密钥?

问题描述

我想从JSON(实际上是JSON模式)创建密钥列表。 JSON是复杂且嵌套的,因此我正在使用jsonpath-ng库。

我无法获取键列表。另一方面,使用以下语法成功提取值print([match.value for match in tagNames])

尝试使用类似的语法提取密钥,像这样...

from jsonpath_ng import jsonpath,parse
import json

filePath = "./sample.json"
with open(filePath,"r") as jsonFile:
    jsonData = json.load(jsonFile)

tagNames = parse("tags[*].*").find(jsonData)
print([match.key for match in tagNames])

返回此错误

AttributeError:'DatumInContext'对象没有属性'key'

尽管我在键入“匹配”后得到了“关键”建议。

我使用的JSON示例:

{
"tags": [
    {
        "name": "auth","description": "Authentication"
    },{
        "name": "b2b","description": "B 2b"
    }
],"paths": {
    "/rest/auth": {
        "post": {
            "tags": [
                "auth"
            ],"operationId": "generatetoken","consumes": [
                "application/json"
            ],"produces": [
                "*/*"
            ],"responses": {
                "200": {
                    "description": "Generated"
                },"201": {
                    "description": "Created"
                }
            }
        },"get": {
            "tags": [
                "status"
            ],"operationId": "check Token","201": {
                    "description": "Created"
                }
            }
        }
    }
}

}

任务1-在标签获取键的简单任务(预期结果:名称,说明)。

任务2-更复杂的情况是从路径获取密钥(预期结果:post,get)。

如果jsonpath不支持提取密钥,那么有人对嵌套JSON有其他建议吗?

我还尝试将匹配结果转换为纯python字典,以便使用.keys()获得密钥,但没有成功。

解决方法

如果我对您的理解正确,那么您可能正在寻找这样的东西:

from jsonpath_ng import parse
import json
my_str = """[your json string above]"""
data = json.loads(my_str)

第一个表达式:

sonpath_expr = parse('$.tags')
for d in jsonpath_expr.find(data):
    for k in d.value[0].keys():
        print(k)

输出:

name
description

第二个表达式:

jsonpath_expr = parse('$.paths..*..*')
for k in jsonpath_expr.find(data)[0].context.value.keys():
    print(k)

输出:

post
get