[英]List Indices in json in Python
I've got a json file that I've pulled from a web service and am trying to parse it. 我有一个从网络服务中提取的json文件,正在尝试对其进行解析。 I see that this question has been asked a whole bunch, and I've read whatever I could find, but the json data in each example appears to be very simplistic in nature.
我看到这个问题已经被问了一整堆了,我已经阅读了所有可以找到的内容,但是每个示例中的json数据在本质上似乎非常简单。 Likewise, the json example data in the python docs is very simple and does not reflect what I'm trying to work with.
同样,python文档中的json示例数据非常简单,不能反映我要使用的内容。 Here is what the json looks like:
这是json的样子:
{"RecordResponse": {
"Id": blah
"Status": {
"state": "complete",
"datetime": "2016-01-01 01:00"
},
"Results": {
"resultNumber": "500",
"Summary": [
{
"Type": "blah",
"Size": "10000000000",
"OtherStuff": {
"valueOne": "first",
"valueTwo": "second"
},
"fieldIWant": "value i want is here"
The code block in question is: 有问题的代码块是:
jsonFile = r'C:\Temp\results.json'
with open(jsonFile, 'w') as dataFile:
json_obj = json.load(dataFile)
for i in json_obj["Summary"]:
print(i["fieldIWant"])
Not only am I not getting into the field I want, but I'm also getting a key error on trying to suss out "Summary". 我不仅没有进入想要的领域,而且在尝试暂定“摘要”时也遇到了一个关键错误。
I don't know how the indices work within the array; 我不知道索引如何在数组中工作; once I even get into the "Summary" field, do I have to issue an index manually to return the value from the field I need?
我什至进入“摘要”字段后,是否必须手动发布索引以从所需的字段返回值?
The example you posted is not valid JSON (no commas after object fields), so it's hard to dig in much. 您发布的示例不是有效的JSON(对象字段后没有逗号),因此很难深入研究。 If it's straight from the web service, something's messed up.
如果直接来自Web服务,那就有些麻烦了。 If you did fix it with proper commas, the "Summary" key is within the "Results" object, so you'd need to change your loop to
如果您确实使用正确的逗号对其进行了修复,则“摘要”键位于“结果”对象内,因此您需要将循环更改为
with open(jsonFile, 'w') as dataFile:
json_obj = json.load(dataFile)
for i in json_obj["Results"]["Summary"]:
print(i["fieldIWant"])
If you don't know the structure at all, you could look through the resulting object recursively: 如果您根本不了解结构,则可以递归浏览结果对象:
def findfieldsiwant(obj, keyname="Summary", fieldname="fieldIWant"):
try:
for key,val in obj.items():
if key == keyname:
return [ d[fieldname] for d in val ]
else:
sub = findfieldsiwant(val)
if sub:
return sub
except AttributeError: #obj is not a dict
pass
#keyname not found
return None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.