简体   繁体   中英

Extracting data from nested dictionary JSON file

I am trying to access the keys of first dictionary, and the color red only from the list to put them in multidimensional array.

{
  "100": {
     "pass": "edrsf45tf"
     "colors": ["red", "blue"]
  },
  "101": {
     "pass": "trf56trt"
     "colors": ["red", "black", "white"]
  }
}
y_train = []

with open('/data.json') as data:
    accessData = json.load(data)
    for i in range(len(accessData)):
        y_train.append(acessData[i]['colors']

I'm stuck here, with this desired output:

id    color
100   red
101   red
102   null 
...   ...
300   red

Once you load the JSON and save it to a dictionary, you can go like this if red color is the first in the colors key:

jdct = { "100": { "pass": "edrsf45tf", "colors" :["red", "blue" ] }, 
    "101": { "pass": "trf56trt", "colors": ["red", "black", "white" ] } }
for k,v in jdct.items():
    print(k, v["colors"][0])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM