-1

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

aerioeus
  • 1,348
  • 1
  • 16
  • 41

3 Answers3

0

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?

DaveR
  • 1,696
  • 18
  • 24
0

This will give you the list of products

products = [ item['product'] for item in data['articles']]
Shashikamal R C
  • 512
  • 3
  • 8
0

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']
Rownum Highart
  • 187
  • 1
  • 13