Home > front end >  Retrieval of particular object from JSON response in Python
Retrieval of particular object from JSON response in Python

Time:10-18

I have following data and need to retrieve items from object name "item". In some cases it can be an array. I am unable to figure out how to do it in python. I have to iterate these values and then put them in a MYSQL database. When the response is an array then I cannot iterate with the same loop which I use for single value.

a_dict = {"ZWAS.Response": {"DATA_TT": {
"item": {"MNNS": "000000000100000134", "CBBB": "16667.000", "HARO": "004H", "MSPR": "000000004000000059",
         "BDD": "2022-10-16", "MTT": "04:15:00"}}}}
b_dict = {"ZWAS.Response": {"DATA_TT": {"item": [
{"MNNS": "000000000100000134", "CBBB": "16667.000", "HARO": "004H", "MSPR": "000000004000000059",
 "BDD": "2022-10-16", "MTT": "04:15:00"},
{"MNNS": "000000000100000134", "CBBB": "16667.000", "HARO": "004H", "MSPR": "000000004000000059",
 "BDD": "2022-10-16", "MTT": "04:15:00"}]}}}


for key in a_dict.keys():
    print(key, '->', a_dict[key])

for value in a_dict.values():
    print(value)

k1 = a_dict['ZWAS.Response']
k2 = k1['DATA_TT']
mydata = k2['item']
print(len(mydata))

CodePudding user response:

Best option would be to fix the input data so that item key always contains a list, even when there's only a single item.

But if you can't do that then you need some code like this:

def process_data(data):
    value = data["ZWAS.Response"]["DATA_TT"]["item"]
    if isinstance(value, list):
        items = value
    else:
        items = [value]

    for item in items:
        # whatever you want to do here:
        print(item["MNNS"])

process_data(a_dict)
process_data(b_dict)

CodePudding user response:

Check type of "item" with isinstance function:

item = k2['item']

if isinstance(item, list):
    print("Item is list")
    for x in item:
        print(len(x))
elif isinstance(item, dict):
     print("Item is dict")
     print(len(item))
else:
     print("Item is something else")
  • Related