4

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.

1 Answer 1

6

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 ""
Sign up to request clarification or add additional context in comments.

2 Comments

Please improve this example by showing creation of the myJson object.
you can load the json for example with json.loads('your json string like upper example') hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.