解析 JSON 失败,因为出现字符串而不是 dicts/lists [英] Parsing JSON fails as strings appear instead of dicts/lists

查看:28
本文介绍了解析 JSON 失败,因为出现字符串而不是 dicts/lists的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

with open('twit/example.json', encoding='utf8') as json_data:
    for line in json_data:
        try:
            dataText = json.loads(line)
        except ValueError:
            continue

for a in dataText:
    print(a["user"]["location"])

结果是:字符串索引必须是整数

更新:以下答案用于打印

Update: The below answer is for printing

print(dataText["user"]["location"])

现在我想要这个:

print(a["user"]["location"])

推荐答案

如果您的 json 文件是普通格式,请改用:

If your json file is in a normal format, use this instead:

with open('twit/example.json', encoding='utf8') as json_data:
    dataText = json.loads(line)

for a in dataText:
    print(dataText["user"]["location"])

你的代码目前的编写方式让我觉得你在一个文件中有多个 json 结构,用新行分隔.这不是 json 通常的格式.

The way your code is currently written makes me think you have multiple json structures in a single file, separated by new lines. This is not how json is usually formatted.

这篇关于解析 JSON 失败,因为出现字符串而不是 dicts/lists的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆