简体   繁体   English

如何使用 python 从 json output 中提取

[英]how do you extract from the json output using python

I have a json output from http request like this:我有一个来自 http 的 json output 请求,如下所示:

print(resp)
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-12345', 'displayName': 'beff'}]}
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-7898', 'displayName': 'dude101'}]}
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-56890', 'displayName': 'prop'}]}

I need to grab the entityId from this list:我需要从这个列表中获取 entityId:

HOST-12345
HOST-7898
HOST-56890

I have this:我有这个:

print(resp['entities']['entityId'])

I get this error:我收到此错误:

TypeError: list indices must be integers or slices, not str

indices are always number, so to access line number 1 you have to write resp[0], now using dots (.) you can access the inside fields.索引始终是数字,因此要访问第 1 行,您必须编写 resp[0],现在使用点 (.) 您可以访问内部字段。 print(resp[0]['entities'][0]['entityId']) print(resp[0]['entities'][0]['entityId'])

Your current response is not the in JSON format in fact, if this is what it is, you need to first split it with "\n" to get every line as a list item.实际上,您当前的响应不是 JSON 格式,如果是这样,您需要先用"\n"将其拆分以将每一行作为列表项。 Then you need to convert ' to " . Now you can Decode it with json.loads to get the dictionary object and get information from it:然后您需要将'转换为" 。现在您可以使用json.loads对其进行解码以获取字典 object 并从中获取信息:

import json

txt = """{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-12345', 'displayName': 'beff'}]}
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-7898', 'displayName': 'dude101'}]}
{'totalCount': 1, 'pageSize': 50, 'entities': [{'entityId': 'HOST-56890', 'displayName': 'prop'}]}"""

for line in txt.split('\n'):
    correct_json_format = line.replace("'", '"')
    d = json.loads(correct_json_format)
    print(d['entities'][0]['entityId'])

output: output:

HOST-12345
HOST-7898
HOST-56890

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

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