0

我需要在 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"
}]

有什么帮助吗?谢谢你

4

1 回答 1

1

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

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
于 2021-05-28T12:32:36.280 回答