简体   繁体   English

将 JSON LINES 文件转换为 JSON 格式?

[英]Convert JSON LINES file to JSON format?

I have file (around 6 GB) that each line is JSON.我有文件(大约 6 GB),每行都是 JSON。

{"name":"name1", "age":40, "car":null}
{"name":"name2", "age":30, "car":null}
{"name":"name3", "age":30, "car":null}

How can I convert it into a JSON array with Python?如何使用 Python 将其转换为 JSON 数组?

import fileinput
for line in fileinput.input("test.txt", inplace=True):
    if 1 != fileinput.filelineno():
        print(',{}'.format(line), end='')
    else:
        print('[{}'.format(line), end='')
open("test.txt","a").write(']')
     

Load each line and save it into a list.加载每一行并将其保存到列表中。

with open('file.txt', 'r') as in_file:
    lines = [json.loads(line) for line in in_file.readlines()]

Then you can save that to a file like with json.dump()然后你可以把它保存到一个文件中,比如json.dump()

with open('out.json', 'w') as out_file:
    json.dump(lines, out_file)

如何将 .Json 文件转换为 .jsonline

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM