Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I use jsonpath in python? (jsonpath_ng.ext)

I have a json data object and want to return a specific value like in XML with xpath. But on json with jsonpath.

The documentation is ok, but I miss a good example.

like image 272
Markus Avatar asked Oct 22 '25 02:10

Markus


1 Answers

Because I had about 1 day to understand how it works and missed an example in the docs (https://pypi.python.org/pypi/jsonpath-ng/1.4.2), I post my code example here.

example for a structure like this:

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

                    }
                ],
                "type": "device_info"
            },
            {....}
            ]

The code to get a value of an ability and property:

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 ""
like image 90
Markus Avatar answered Oct 23 '25 15:10

Markus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!