Home > OS >  Python read every json object and assign variable to each data line
Python read every json object and assign variable to each data line

Time:10-16

I have this json file:

{
    "id": "manager",
    "children": [
        {
            "id": "user1",
            "children": [],
            "data": {
                "name": "john",
                "age": "55",
                "lastname": "smith",
            }
        },
        {
            "id": "user2",
            "children": [],
            "data": {
                "name": "mark",
                "age": "56",
                "lastname": "guri",
            }
        },
        {
            "id": "user3",
            "children": [],
            "data": {
                "name": "alex",
                "age": "57",
                "lastname": "muller",
            }
        }
    ],
    "data": {
        "name": "sukri",
        "age": "24",
        "lastname": "adam"
    }
}

I am trying to assign a variable to each of those information under children. so I can access them later on..

The challenge is to iterate through all children under manager.
Result should be like:
children1{id=user1, name=john, age="55"}
children2{...}
children3{...}

And it should go to the end of the list and capture all info.

Please let me know how to achieve this. I have the following code which doesn't work:

with open('data.json') as json_file:
    data = json.load(json_file)
    print ("id:", data['manager'])
    print ("")
    for children in data['manager']:
        print("name:", children['name'])
        print("age:", children['age'])
        print("lastname:", children['lastname'])
        print("")

CodePudding user response:

You could create a list with the data for each of the children with something like this.

import json

with open('data.json') as json_file:
    data = json.load(json_file)

children = [child['data'] for child in data['children']]

print(children)
[{'name': 'john', 'age': '55', 'lastname': 'smith'}, {'name': 'mark', 'age': '56', 'lastname': 'guri'}, {'name': 'alex', 'age': '57', 'lastname': 'muller'}]

Alternatively, you could create a dictionary of the children with this.

children_dict = {f'user{id 1}': child['data'] for id, child in enumerate(data['children'])}

print(children_dict['user1'])
{'name': 'john', 'age': '55', 'lastname': 'smith'}
  • Related