简体   繁体   English

列表中的字典索引

[英]Indexing of dictionaries in list

I'm new to Python and I am currently trying to work with JSON files in Python.我是 Python 的新手,我目前正在尝试使用 Python 中的 JSON 文件。 My JSON file looks as follows (please ignore the content):我的 JSON 文件如下(内容请忽略):

    [{
  "Id" : "5444",
  "date" : "2012-02-01",
  "data" : [ {
    "Name" : "Fred Smith",
    "Sex" : "Male",
    "description" : "{\"car\": \"Suzuki\", \"salary\": 100000, \"married\": null}"
  }, {
    "occupation" : "smith",
    "City" : "New York",
    "data" : "{\"height\": \"6ft\", \"GMATscores\": [{\"verbal\": \"None\", \"reasoning\": 200, \"numerical\": 0.0}]}"
  } ]
} ]

I have been struggling for hours, how do I extract the value for "reasoning: 200" out of this mess?我已经挣扎了几个小时,我如何从这个烂摊子中提取“推理:200”的价值?

you can use json module:您可以使用json模块:

import json 



my_json = [{
  "Id" : "5444",
  "date" : "2012-02-01",
  "data" : [ {
    "Name" : "Fred Smith",
    "Sex" : "Male",
    "description" : "{\"car\": \"Suzuki\", \"salary\": 100000, \"married\": null}"
  }, {
    "occupation" : "smith",
    "City" : "New York",
    "data" : "{\"height\": \"6ft\", \"GMATscores\": [{\"verbal\": \"None\", \"reasoning\": 200, \"numerical\": 0.0}]}"
  } ]
} ]

inner_json = json.loads(my_json[0]['data'][1]['data'])

# {'height': '6ft',
# 'GMATscores': [{'verbal': 'None', 'reasoning': 200, 'numerical': 0.0}]}

inner_json['GMATscores'][0]['reasoning']
# 200

The JSON data you added here is not really clean.您在此处添加的 JSON 数据不是很干净。 It's a mix of json and escaped string value.它是 json 和转义字符串值的混合。 The data inside your second 'data' key is a string, so that needs to be json.loaded first.第二个“数据”键中的数据是一个字符串,因此需要先加载 json.loaded。

json1 = [{
  "Id" : "5444",
  "date" : "2012-02-01",
  "data" : [ {
    "Name" : "Fred Smith",
    "Sex" : "Male",
    "description" : "{\"car\": \"Suzuki\", \"salary\": 100000, \"married\": null}"
  }, {
    "occupation" : "smith",
    "City" : "New York",
    "data" : "{\"height\": \"6ft\", \"GMATscores\": [{\"verbal\": \"None\", \"reasoning\": 200, \"numerical\": 0.0}]}"
  } ]
} ]


json2 = json.loads(j[0]['data'][1]['data'])

print(json2['GMATscores'][0]['reasoning'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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