解析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"]) 
+0

json文件是什么样的? – codeiscool

+0

它是来自API的Twitter的json文件,我想打印每个推文在文件中的位置。 – Mahran

+0

见我的回答则 – codeiscool

如果你的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通常如何格式化的方式。

+0

它说文件“”,第5行 了在dataText: ^ IndentationError:编辑的代码意外取消缩进 – Mahran

+0

,再试一次,但删除'试试:'以及 – codeiscool

+0

之前的4个空格,谢谢您的帮助,, – Mahran