如何在python中使用jsonpath?(jsonpath_ng.ext)

Mar*_*kus 2 python json jsonpath

我有一个 json 数据对象,想返回一个特定的值,比如在 XML 中使用 xpath。但是在带有 jsonpath 的 json 上。

文档还可以,但我错过了一个很好的例子。

Mar*_*kus 6

因为我有大约 1 天的时间来了解它是如何工作的并且错过了文档中的一个示例(https://pypi.python.org/pypi/jsonpath-ng/1.4.2),所以我在这里发布了我的代码示例。

像这样的结构的例子:

"abilities": [
            {
          ...
                "name": "device_info",
                "properties": [
                    {
                        "name": "manufacturer",
                        "value": "xxxx",
                    },
                    {
                        "name": "product",
                        "value": "yyy",

                    }
                ],
                "type": "device_info"
            },
            {....}
            ]
Run Code Online (Sandbox Code Playgroud)

获取能力和属性值的代码:

from jsonpath_ng.ext import parse

abilityname = "device_info"
propertyname = "manufacturer"
result = parse('$[?(@.name=="' + abilityname + '")].properties[?(@.name=="' + propertyname + '")]').find(myJson)
if len(result) == 1:
    return str(result[0].value['value'])
else:
    return ""
Run Code Online (Sandbox Code Playgroud)