Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python: Extract all specific subkeys from JSON

If I have JSON similar to as follows:

"children": [
        {
            "firstName": "Alice",
            "age": 6
        },
        {
            "firstName": "Bob",
            "age": 8
        }
        {
            "firstName": "Candice",
            "age": 4
        }
    ]

And I want an array of all firstName values, how would I go about getting them with python?

I have tried the following and it works, but my data set is on the larger side (40,000 lines) and it would be impractical to repeat it:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

children = JSON

firstNames = []

firstNames.append(json.loads(children.text)['children'][0]['firstName'])
firstNames.append(json.loads(children.text)['children'][1]['firstName'])
firstNames.append(json.loads(children.text)['children'][2]['firstName'])

I have considered using a for loop to replace the numbers but have no idea how to go about doing so.

>Solution :

@asher, you can significantly improve performance if you run de-serialization only once. And to collect the names you can use the list comprehension:

doc = json.loads(children.text)
firstNames = [child["firstname"] for child in doc["children"]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading