在python中将ndjson转换为json

问题描述

我需要在 python 中将 ndjson 对象转换为 json 我看到 pypi.org 中有一个库,但我无法使用它 它是 ndjson 0.3.1

{"license":"mit","count":"1551711"}
{"license":"apache-2.0","count":"455316"}
{"license":"gpl-2.0","count":"376453"}

进入json

[{
    "license": "mit","count": "1551711"
},{
    "license": "apache-2.0","count": "455316"
},{
    "license": "gpl-2.0","count": "376453"
}]

有什么帮助吗? 谢谢

解决方法

无需使用第三方库,Python 的 json 标准库就足够了:

import json

# the content here could be read from a file instead
ndjson_content = """\
{"license":"mit","count":"1551711"}\n\
{"license":"apache-2.0","count":"455316"}\n\
{"license":"gpl-2.0","count":"376453"}\n\
"""

result = []

for ndjson_line in ndjson_content.splitlines():
    if not ndjson_line.strip():
        continue  # ignore empty lines
    json_line = json.loads(ndjson_line)
    result.append(json_line)

json_expected_content = [
    {"license": "mit","count": "1551711"},{"license": "apache-2.0","count": "455316"},{"license": "gpl-2.0","count": "376453"}
]

print(result == json_expected_content)  # True