【发布时间】:2021-12-30 22:25:19
【问题描述】:
我有一个大文件(大约 3GB),其中包含看起来像 JSON 文件但不是因为它在“观察”或 JSON 对象之间缺少逗号(,)(我的这些“对象”中有大约 200 万个)数据文件)。
例如,这就是我所拥有的:
{
"_id": {
"$id": "fh37fc3huc3"
},
"messageid": "4757724838492485088139042828",
"attachments": [],
"usernameid": "47284592942",
"username": "Alex",
"server": "475774810304151552",
"text": "Must watch",
"type": "462050823720009729",
"datetime": "2018-08-05T21:20:20.486000+00:00",
"type": {
"$numberLong": "0"
}
}
{
"_id": {
"$id": "23453532dwq"
},
"messageid": "232534",
"attachments": [],
"usernameid": "273342",
"usernameid": "Alice",
"server": "475774810304151552",
"text": "https://www.youtube.com/",
"type": "4620508237200097wd29",
"datetime": "2018-08-05T21:20:11.803000+00:00",
"type": {
"$numberLong": "0"
}
这就是我想要的(“观察”之间的逗号):
{
"_id": {
"$id": "fh37fc3huc3"
},
"messageid": "4757724838492485088139042828",
"attachments": [],
"username": "Alex",
"server": "475774810304151552",
"type": {
"$numberLong": "0"
}
},
{
"_id": {
"$id": "23453532dwq"
},
"messageid": "232534",
"attachments": [],
"usernameid": "Alice",
"server": "475774810304151552",
"type": {
"$numberLong": "0"
}
这是我尝试过的,但在我需要的地方没有逗号:
import re
with open('dataframe.txt', 'r') as input, open('out.txt', 'w') as output:
output.write("[")
for line in input:
line = re.sub('', '},{', line)
output.write(' '+line)
output.write("]")
如何才能在数据文件中的每个 JSON 对象之间添加逗号?
【问题讨论】:
-
请注意,即使有逗号,它仍然不是合法的 JSON。
-
您所做拥有的是一个有效的 JSON 对象流。
jq实用程序可以轻松地将其转换为单个 JSON 对象数组:jq -s '.' dataframe.txt。有一个用于 Python 的jq绑定库,但不幸的是,它需要将整个 JSON 读入内存。理想情况下,您会使用 Python 流式 JSON 库,它也可以处理对象流,但我没有任何好的建议。 -
如果该行只是一个右大括号而没有其他内容,请在后面添加一个逗号。但不要在最后一行这样做。
-
考虑到大小,如果它精确地采用这种格式,如果速度有任何问题,我会选择
sed或awk而不是Python。按照约翰戈登的说法。修剪最后一个逗号或检查 sed awk 中的下一行是否有内容。