我从这里开始:
url = 'https://api.example.com/'
bearer_token = 'my_token'
result = requests.get(url,headers={'Content-Type':'application/json','Authorization': 'Bearer {}'.format(bearer_token)}).json()
print(result[3])
当我打印 JSON 结果生成的结果的 type
时,我得到一个“列表”,但我无法像通常分析列表的方式解析它。例如,我无法访问 [ 和 { 后面的键。当我尝试解析其中的数据时,这些区域似乎受到不同的对待。有些值可以通过 [index]['key'] 访问,其他值则不能。
这是我 print(result[3])
时 JSON 输出的片段:
{'created_at': 'Wed Oct 1 10:20:16 +0000 2021', 'id': 1448292507, 'id_str': '1448817927', 'text': 'Lorem ipsum data data data', 'truncated': True, 'entities': {'hashtags': [{'text': 'RedLife', 'indices': [90, 101]}, {'text': 'NS18', 'indices': [102, 107]}], 'symbols': [], 'user_ment': [{'n_name': 'name_1', 'name': 'name_2', 'id': 5232, 'id_str': '32', 'indices': [12, 10]}, {'n_name': 'Lorem', 'name': 'Lorem', 'id': 1372, 'id_str': '72', 'indices': [10, 17]}, {'n_name': 'TV', 'name': 'TV', 'id': 3576, 'id_str': '76', 'indices': [55, 60]}], 'urls': [{'url': 'https://website.com', 'expanded_url': 'https://website'...}
当我print(result[3]['created_at'])
时,我得到Wed Oct 1 10:20:16 +0000 2021
。太棒了!
当我尝试列表中的其他键时,我收到 KeyError
s。
我需要对 JSON 数据执行什么操作才能提取我需要的所有数据?如果存在同一“键”的多个实例,如何检索我正在寻找的“值”?我是否只附加我想要的索引,如下所示:print(result[3]['n_name'][0])
?
最佳答案
要访问n_name
,您在字典中缺少'entities'
和'user_ment'
级别,然后您有一个列表,然后又是一个列表
result = [
{},
{},
{},
{'created_at': 'Wed Oct 1 10:20:16 +0000 2021', 'id': 1448292507,
'id_str': '1448817927',
'text': 'Lorem ipsum data data data', 'truncated': True,
'entities': {
'hashtags': [{'text': 'RedLife', 'indices': [90, 101]}, {'text': 'NS18', 'indices': [102, 107]}],
'symbols': [],
'user_ment': [
{'n_name': 'name_1', 'name': 'name_2', 'id': 5232, 'id_str': '32', 'indices': [12, 10]},
{'n_name': 'Lorem', 'name': 'Lorem', 'id': 1372, 'id_str': '72', 'indices': [10, 17]},
{'n_name': 'TV', 'name': 'TV', 'id': 3576, 'id_str': '76', 'indices': [55, 60]}
],
'urls': [{'url': 'https://website.com', 'expanded_url': 'https://website'}]
}}
]
x = result[3]['entities']['user_ment'][0]['n_name']
print(x) # name_1
x = result[3]['entities']['user_ment'][1]['n_name']
print(x) # Lorem
关于python - 无法解析 [{ 和 }] Python 之间返回的 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69560056/