从JSON到JSONL的Python转换

Lea*_*wly 10 python json

我希望将标准JSON对象处理为一个对象,其中每行必须包含一个单独的,自包含的有效JSON对象。查看JSON行

JSON_file =

[{u'index': 1,
  u'no': 'A',
  u'met': u'1043205'},
 {u'index': 2,
  u'no': 'B',
  u'met': u'000031043206'},
 {u'index': 3,
  u'no': 'C',
  u'met': u'0031043207'}]
Run Code Online (Sandbox Code Playgroud)

To JSONL

{u'index': 1, u'no': 'A', u'met': u'1043205'}
{u'index': 2, u'no': 'B', u'met': u'031043206'}
{u'index': 3, u'no': 'C', u'met': u'0031043207'}
Run Code Online (Sandbox Code Playgroud)

我当前的解决方案是将JSON文件读取为文本文件,并[从开头和]结尾删除。因此,在每行上创建一个有效的JSON对象,而不是在包含行的嵌套对象上创建一个有效的JSON对象。

我想知道是否有更优雅的解决方案?我怀疑在文件上使用字符串操作可能会出错。

目的是json在Spark上将文件读入RDD。查看相关问题- 使用Apache Spark读取JSON-`corrupt_record`

wou*_*lee 20

jsonlines包正好由为您的使用情况:

import jsonlines

items = [
    {'a': 1, 'b': 2},
    {'a', 123, 'b': 456},
]
with jsonlines.open('output.jsonl', 'w') as writer:
    writer.write_all(items)
Run Code Online (Sandbox Code Playgroud)

(是的,我是在您发布原始问题几年后写的。)


Mar*_*ers 16

您的输入似乎是一系列Python对象;它当然不是有效的JSON文档。

如果您有Python字典的列表,那么您要做的就是将每个条目分别转储到文件中,然后换行:

import json

with open('output.jsonl', 'w') as outfile:
    for entry in JSON_file:
        json.dump(entry, outfile)
        outfile.write('\n')
Run Code Online (Sandbox Code Playgroud)

json模块的默认配置是输出不嵌入换行符的JSON。

假设你的ABC名称是真正的弦乐,会产生:

{"index": 1, "met": "1043205", "no": "A"}
{"index": 2, "met": "000031043206", "no": "B"}
{"index": 3, "met": "0031043207", "no": "C"}
Run Code Online (Sandbox Code Playgroud)

如果您从包含条目列表的JSON文档开始,只需先使用json.load()/ 解析该文档json.loads()


Jon*_*ira 10

执行此操作的一个简单方法是使用jq终端中的命令。

jqDebian及其衍生版本上安装:

sudo apt-get install jq
Run Code Online (Sandbox Code Playgroud)

CentOSRHEL用户应运行:

sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
sudo yum install jq -y
Run Code Online (Sandbox Code Playgroud)

基本用法:

jq -c '.[]' some_json.json >> output.jsonl
Run Code Online (Sandbox Code Playgroud)

如果您需要处理大文件,我强烈建议使用该--stream标志。这将以jq流模式解析您的 JSON 内容。

jq -c --stream '.[]' some_json.json >> output.json
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要在 Python 文件中执行此操作,您可以使用bigjson一个有用的库,它可以在流模式下解析 JSON:

pip3 install bigjson
Run Code Online (Sandbox Code Playgroud)

要读取一个巨大的 JSON 文件(在我的例子中,它是 40 GB):

import bigjson

# Reads JSON file in streaming mode
with open('input_file.json', 'rb') as f:
    json_data = bigjson.load(f)

    # Open output file
    with open('output_file.jsonl', 'w') as outfile:
        # Iterates over input json
        for data in json_data:
            # Converts json to a Python dict
            dict_data = data.to_python()

            # Saves the output to output file
            outfile.write(json.dumps(dict_data)+"\n")
Run Code Online (Sandbox Code Playgroud)

如果需要,请尝试并行化此代码以提高性能。将结果发布在这里:)

文档和源代码:bigjson