简体   繁体   English

访问 JSON 嵌套 arrays 在 Python

[英]Access JSON nested arrays in Python

I'm new to Python and I'm trying to process something and having no luck finding the answer or if it's already been asked.我是 Python 的新手,我正在尝试处理某些事情,但没有找到答案或者是否已经被问到。 I'm making a call to an API and receiving some data back as JSON.我正在调用 API 并以 JSON 的形式接收一些数据。 I'm stripping out certain bits that I don't need with the keys being stripped out and only the values remaining which wouldn't be a problem but I can't get into them as the keys I want to access are nested in an array.我正在剥离某些我不需要的位,而密钥被剥离,只有剩余的值不会成为问题,但我无法进入它们,因为我想要访问的密钥嵌套在一个大批。

I've been accessing the data and can get up to json.dumps(payload['output']['generic']) but I can't seem to find any information online as to how I can access these last values only.我一直在访问数据,最多可以访问 json.dumps(payload['output']['generic']) 但我似乎无法在网上找到任何关于如何仅访问这些最后值的信息。

Apologies in advance if this question already exists.如果这个问题已经存在,请提前道歉。

 { "output": { "generic": [ { "response_type": "text", "text": "hi" } ], "intents": [ { "intent": "CollectionDate", "confidence": 0.8478035449981689 } ], "entities": [ { "entity": "Payslip", "location": [ 19, 26 ], "value": "When is my collection date", "confidence": 1 } ] }, "context": { "global": { "system": { "turn_count": 10 } }, "skills": { "main skill": { "user_defined": { "DemoContext": "Hi," }: "system": {} } } } }

To clarify:澄清:

I want to access the "text", "intent" and "confidence"我想访问“文本”、“意图”和“信心”

at the moment I'm printing the value posted and then the responses for the sections I want like the below.目前我正在打印发布的值,然后是我想要的部分的响应,如下所示。

print(x)
print(json.dumps(payload['output']['generic']))
print(json.dumps(payload['output']['intents']))

Use following code to convert the json to a dict first:首先使用以下代码将 json 转换为字典:

json_data = json.loads(str(yourData))

After that, in your case, the outermost key is "output", and it is another dict, so just use json_data['output'] to access the content inside.之后,在你的情况下,最外面的键是“输出”,它是另一个字典,所以只需使用json_data['output']来访问里面的内容。

For other keys inside of the "output", like "generic", you can see it is an array with the [] brackets.对于“输出”内的其他键,例如“通用”,您可以看到它是一个带有 [] 括号的数组。 use json_data['output'][index] first to get the content inside, then use the same method you access a dict to access the content inside of keys like this.首先使用json_data['output'][index]来获取里面的内容,然后使用与访问 dict 相同的方法来访问这样的键内部的内容。

They key here is that the Traceback error indicates an issue with indexing a "List"他们的关键是 Traceback 错误表明索引“列表”存在问题

This is because a "List" type is a valid JSON type, and generic contains a list of length 1, with a dict inside!这是因为“列表”类型是有效的 JSON 类型,并且generic包含长度为 1 的列表,其中包含一个 dict!

>>> payload['output']['generic']['text']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not str
>>> type(payload['output']['generic'])
<class 'list'>
>>> len(payload['output']['generic'])
1
>>> payload['output']['generic'][0]
{'response_type': 'text', 'text': 'hi'}
>>> type(payload['output']['generic'][0])
<class 'dict'>
>>> payload['output']['generic'][0]['text']
'hi'
>>>

So, given your expected input JSON format, you will need to know how to index in to pull each required data point.因此,鉴于您预期的输入 JSON 格式,您将需要知道如何索引以提取每个所需的数据点。

There are a few packages, glom is one, that will help you deal with missing values from API generated JSON.有几个包,glom 就是其中之一,可以帮助您处理 API 生成的 JSON 中的缺失值。

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

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