3

I've got some JSON like the following:

{
"books": [
    {
        "name": "Matthew"
    },
    {
        "name": "Mark",
        "sections": [
            {
                "reference": "1:1-1:8",
                "tags": [
                    "a",
                    "b"
                ],
                "summary": "blah",
                "notes": ""
            },
            {
                "reference": "1:9-1:15",
                "tags": [
                    "b",
                    "c",
                    "d"
                ],
                "summary": "",
                "notes": ""
            }
        ]
    }
]

}

I want to get a list of all sections using objectpath.

I've tried:

sections = Tree(db).execute('$.books[@.name is "Mark"].sections')
for section in sections:
    print(section)
    print("----\n")

but what is returned is a single section, which is an array. That is sections only has a single result while I am expecting (or at least wanting) just the array of 'sections'. This would save me having a for loop in a for loop.

Is there some special syntax to make it return how I want?

I've also tried:

'$.books[@.name is "Mark"].sections.*'
'$.books[@.name is "Mark"].sections[*]'

with no luck.

2
  • 2
    What's wrong with the python json library? [book['sections'] for book in json.loads(json_obj)['books']] Commented Aug 7, 2018 at 13:06
  • I"m using objectpath to help divorce the data structure from the code, so want to keep just a few strings in objectcode makes changing data layout very easy. Commented Aug 8, 2018 at 2:12

1 Answer 1

2

sections is a generator object. To get the first item from it you can use next() function:

sections = Tree(db).execute('$.books[@.name is "Mark"].sections')
print(sections) # will show that it's a generator
for section in next(sections):
    print(section)
    print("----\n")

This first item will be the list with individual sections. Now you can iterate over each section using for loop.

Sign up to request clarification or add additional context in comments.

1 Comment

This example helped me to extract a value from a nested json perfectly. Thanks

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.