Search code examples
pythonjsonpytestnested-json

Writing a program to take user input and prints output from the Nested json file


I have a nested json file with the below data and I need some help in writing an interactive program where it should take a topping as input and prints out the names of all the donuts that have this topping.

[
    {
        "id": "0001",
        "type": "donut",
        "name": "Cake",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" },
                        { "id": "1002", "type": "Chocolate" },
                        { "id": "1003", "type": "Blueberry" },
                        { "id": "1004", "type": "Devil's Food" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5007", "type": "Powdered Sugar" },
                { "id": "5006", "type": "Chocolate with Sprinkles" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    },
    {
        "id": "0002",
        "type": "donut",
        "name": "Raised",
        "ppu": 0.55,
        "batters":
            {
                "batter":
                    [
                        { "id": "1001", "type": "Regular" }
                    ]
            },
        "topping":
            [
                { "id": "5001", "type": "None" },
                { "id": "5002", "type": "Glazed" },
                { "id": "5005", "type": "Sugar" },
                { "id": "5003", "type": "Chocolate" },
                { "id": "5004", "type": "Maple" }
            ]
    }
]

What I've tried so far is

import json
f = open('Nested-JSON-1.json')
data = json.load(f)
print(data)

The above code gave the output with all the data from the nested json file

[{'id': '0001', 'type': 'donut', 'name': 'Cake', 'ppu': 0.55, 'batters': {'batter': [{'id': '1001', 'type': 'Regular'}, {'id': '1002', 'type': 'Chocolate'}, {'id': '1003', 'type': 'Blueberry'}, {'id': '1004', 'type': "Devil's Food"}]}, 'topping': [{'id': '5001', 'type': 'None'}, {'id': '5002', 'type': 'Glazed'}, {'id': '5005', 'type': 'Sugar'}, {'id': '5007', 'type': 'Powdered Sugar'}, {'id': '5006', 'type': 'Chocolate with Sprinkles'}, {'id': '5003', 'type': 'Chocolate'}, {'id': '5004', 'type': 'Maple'}]}, {'id': '0002', 'type': 'donut', 'name': 'Raised', 'ppu': 0.55, 'batters': {'batter': [{'id': '1001', 'type': 'Regular'}]}, 'topping': [{'id': '5001', 'type': 'None'}, {'id': '5002', 'type': 'Glazed'}, {'id': '5005', 'type': 'Sugar'}, {'id': '5003', 'type': 'Chocolate'}, {'id': '5004', 'type': 'Maple'}]}, {'id': '0003', 'type': 'donut', 'name': 'Old Fashioned', 'ppu': 0.55, 'batters': {'batter': [{'id': '1001', 'type': 'Regular'}, {'id': '1002', 'type': 'Chocolate'}]}, 'topping': [{'id': '5001', 'type': 'None'}, {'id': '5002', 'type': 'Glazed'}, {'id': '5003', 'type': 'Chocolate'}, {'id': '5004', 'type': 'Maple'}]}]

And then I added below which gave me the error

for type in data['type']:
    for topping in type['topping']:
        print(topping.get('name'))

json.dumps(data)

TypeError: list indices must be integers or slices, not str


Solution

  • Try:

    import json
    
    topping = input('Enter topping: ')
    
    names = []
    with open('data.json') as fp:
        data = json.load(fp)
        for rec in data:
            if rec['type'] == 'donut':
                for top in rec['topping']:
                    if top['type'] == topping:
                        names.append(rec['name'])
    
    if len(names) > 0:
        print('Found matches:')
        print(*[f'- {name}' for name in names], sep='\n')
    else:
        print('No matches found')
    

    Output:

    Enter topping: Sugar
    Found matches:
    - Cake
    - Raised
    
    Enter topping: Cinnamon
    No matches found