我在编程和 Python 方面有点白痴。我知道这些在以前的问题中有很多解释,但是我仔细阅读了所有这些,但没有找到解决方案。
我正在尝试读取一个包含大约 10 亿条数据的 JSON 文件,如下所示:
334465|{"color":"33ef","age":"55","gender":"m"}
334477|{"color":"3444","age":"56","gender":"f"}
334477|{"color":"3999","age":"70","gender":"m"}
我一直在努力克服每行开头的 6 位数字,但我不知道如何读取多个 JSON 对象? 这是我的代码,但我找不到为什么它不起作用?
import json
T =[]
s = open('simple.json', 'r')
ss = s.read()
for line in ss:
line = ss[7:]
T.append(json.loads(line))
s.close()
这是我得到的错误:
ValueError: Extra Data: line 3 column 1 - line 5 column 48 (char 42 - 138)
任何建议都会对我很有帮助!
最佳答案
您的代码逻辑有几个问题。
ss = s.read()
将整个文件 s
读入单个字符串。下一行
for line in ss:
逐一迭代该字符串中的每个字符。所以在每个循环中 line
都是一个字符。在
line = ss[7:]
您将获得除前 7 个字符(位置 0 到 6,包括在内)之外的整个文件内容,并用它替换 line
之前的内容。然后
T.append(json.loads(line))
尝试将其转换为 JSON 并将生成的对象存储到 T
列表中。
这里有一些代码可以满足您的需求。我们不需要使用 .read
将整个文件读入一个字符串,或者使用 .readlines
将整个文件读入一个行列表,我们可以简单地将文件句柄放入一个for 循环,它将逐行遍历文件。
我们使用 with
语句打开文件,这样当我们退出 with
block 或出现 IO 错误时它会自动关闭。
import json
table = []
with open('simple.json', 'r') as f:
for line in f:
table.append(json.loads(line[7:]))
for row in table:
print(row)
输出
{'color': '33ef', 'age': '55', 'gender': 'm'}
{'color': '3444', 'age': '56', 'gender': 'f'}
{'color': '3999', 'age': '70', 'gender': 'm'}
我们可以通过在列表理解中构建 table
列表来使它更紧凑:
import json
with open('simple.json', 'r') as f:
table = [json.loads(line[7:]) for line in f]
for row in table:
print(row)
关于python - 在 Python 中读取包含多个对象的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40712178/