Home > Enterprise >  How to access values in deeply nested json
How to access values in deeply nested json

Time:12-09

I'm having a file that is deeply nested and wondering how I can access the values for Product (details, color, size, material).

  {
     "article": [

      {
       "product":{
        "details": {
        "color": "blue",
        "size": "small",
        "material": "cotton"
        }
      },
      "availability": "in stock",
      "sku": "2317",
      "cost": "$23"
      },
     {
     "product":{
        "details": {
        "color": "red",
        "size": "large",
        "material": "plastic"
        }
     },
     "availability": "no stock",
     "sku": "4342",
     "cost": "$44"
     }
     ],

   "IDs":[
  {
   "name": "Manager",
   "batchID": 3312312
  }
 ]
}

My goal is to iterate over the values for each product using python.

Thank you in advance

CodePudding user response:

This will give you the list of products

products = [ item['product'] for item in data['articles']]

CodePudding user response:

You can do something like this


mydict =   {
     "article": [

      {
       "product":{
        "details": {
        "color": "blue",
        "size": "small",
        "material": "cotton"
        }
      },
      "availability": "in stock",
      "sku": "2317",
      "cost": "$23"
      },
     {
     "product":{
        "details": {
        "color": "red",
        "size": "large",
        "material": "plastic"
        }
     },
     "availability": "no stock",
     "sku": "4342",
     "cost": "$44"
     }
     ],

   "IDs":[
  {
   "name": "Manager",
   "batchID": 3312312
  }
 ]
}

for item in mydict['article']:
    print(item['product'])

Is this what you wanted?

CodePudding user response:

I've put your JSON into JSONPath, and after small trial and error it is evident that you need this JSONPath to access the fields:

$.article[*].product.details

Loop through the array using something like that (sorry, don't have a python env to check properly):

import json

json_data= json.dumps("your_json")

items = json.loads(json_data)
for i in range(0, len(items['article'])):
   print items['article'][i]['product']['details']
  • Related