objectpath json query to get array values in python

1.8k Views Asked by At

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.

1

There are 1 best solutions below

1
On BEST ANSWER

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.