Home > front end >  Parsing nested JSON and collecting data in a list
Parsing nested JSON and collecting data in a list

Time:12-16

I am trying to parse a nested JSON and trying to collect data into a list under some condition.

Input JSON as below:

[
    {
        "name": "Thomas",
        "place": "USA",  
        "items": [
            {"item_name":"This is a book shelf", "level":1},
            {"item_name":"Introduction", "level":1},
            {"item_name":"parts", "level":2},   
            {"item_name":"market place", "level":3},
            {"item_name":"books", "level":1},
            {"item_name":"pens", "level":1},
            {"item_name":"pencils", "level":1}
        ],
        "descriptions": [
            {"item_name": "Books"}  
        ]
    },
    {
        "name": "Samy",
        "place": "UK",  
        "items": [
            {"item_name":"This is a cat house", "level":1},
            {"item_name":"Introduction", "level":1},
            {"item_name":"dog house", "level":3},   
            {"item_name":"cat house", "level":1},
            {"item_name":"cat food", "level":2},
            {"item_name":"cat name", "level":1},
            {"item_name":"Samy", "level":2}
        ],
        "descriptions": [
            {"item_name": "cat"}    
        ]
    }   

]

I am reading json as below:

with open('test.json', 'r', encoding='utf8') as fp:
    data = json.load(fp)
for i in data:
   if i['name'] == "Thomas":
      #collect "item_name", values in a list (my_list) if "level":1
      #my_list = []

Expected output:

my_list = ["This is a book shelf", "Introduction", "books", "pens", "pencils"] 

Since it's a nested complex JSON, I am not able to collect the data into a list as I mentioned above. Please let me know no how to collect the data from the nested JSON.

CodePudding user response:

Try:

import json

with open("test.json", "r", encoding="utf8") as fp:
    data = json.load(fp)

my_list = [
    i["item_name"]
    for d in data
    for i in d["items"]
    if d["name"] == "Thomas" and i["level"] == 1
]
print(my_list)

This prints:

['This is a book shelf', 'Introduction', 'books', 'pens', 'pencils']

Or without list comprehension:

my_list = []
for d in data:
    if d["name"] != "Thomas":
        continue
    for i in d["items"]:
        if i["level"] == 1:
            my_list.append(i["item_name"])

print(my_list)

CodePudding user response:

import json
def get_final_list():
    with open('test.json', 'r', encoding='utf8') as fp:
        data = json.load(fp)

    final_list = []

    for obj in data:
        if obj.get("name") == "Thomas":
            x = list(filter(lambda item: item['level'] == 1, obj.get("items")))
            final_list = final_list   x

    final_list = [i.get("item_name") for i in final_list]

    return final_list
  • Related