解析JSON失败/列出
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"])
结果是:字符串索引必须是整数解析JSON失败/列出
更新:下面的答案是打印
print(dataText["user"]["location"])
现在我想这一个:
print(a["user"]["location"])
如果你的json文件是在一个正常的格式,而不是使用:
with open('twit/example.json', encoding='utf8') as json_data:
dataText = json.loads(line)
for a in dataText:
print(dataText["user"]["location"])
你的代码是目前写让我觉得你有多个JSON结构在一个文件中,以换行分隔的方式。这不是json通常如何格式化的方式。
它说文件“
,再试一次,但删除'试试:'以及 – codeiscool
之前的4个空格,谢谢您的帮助,, – Mahran
json文件是什么样的? – codeiscool
它是来自API的Twitter的json文件,我想打印每个推文在文件中的位置。 – Mahran
见我的回答则 – codeiscool