我一直在将一些推文收集到一个 JSON 文件中,我需要用它对 JSON 中的某些数据进行一些统计。 在谷歌上搜索了几个如何执行此操作的选项后,没有一个能给我正确的解决方案。
JSON 看起来像这样:
{"contributors": null, "truncated": false, "text": .... }
并应用此代码尝试加载它:
import json
f = open("user_timeline_Audi.jsonl",'r')
data = f.read()
print(data)
bla = json.loads(data)
基本上 json.loads()
给我下一个错误:
json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 2698)
最终目标是我需要从多个 JSON 文件中获取 followers_count 和 likes。希望有人能帮忙!
编辑:
根据 Alex Hall 的回答,我现在的代码是:
import json
with open("user_timeline_BMW.jsonl",'r') as f:
for line in f:
obj = json.loads(line)
bla = ["followers_count"]
print(bla)
这只是输出一个列表,而不是它背后的值:
....
['followers_count']
['followers_count']
....
希望有人对这一步有建议!
最佳答案
您正在处理 JSON 行,其中每一行都包含一个 JSON 对象。你应该这样做:
for line in f:
obj = json.loads(line)
然后对每个对象执行您想要的操作。
关于python - 加载 JSON 并获取某些数据 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49218914/