解析 JSON 失败,因为出现的是字符串而不是 dicts/lists
Parsing JSON fails as strings appear instead of 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"])
结果是:字符串索引必须是整数
更新:以下答案用于打印
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 通常的格式。
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"])
结果是:字符串索引必须是整数
更新:以下答案用于打印
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 通常的格式。