python - 无法解析 [{ 和 }] Python 之间返回的 JSON 数据

标签 python json

我从这里开始:

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。太棒了!

当我尝试列表中的其他键时,我收到 KeyErrors。

我需要对 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/

相关文章:

javascript - 为 null javascript 对象成员分配新值

java - 反序列化 JSON 时,RuntimeTypeAdapterFactory 'typeFieldName' 应该适合什么字符串?

javascript - JSON.parse() 不起作用

python - 使用默认 python 解释器而不是安装 virtualenv 解释器的网站

python - 列表未返回正确的值作为输出

python - 错误处理(除以零)

java - 如何将多个 Map<String,String> 解包为 Json

python - 使用类的名称实例化类的对象

python - 使用 Paramiko Transport( channel )使用私钥进行身份验证

java - 在Java中的REST服务中获取空对象