在python中将ndjson转换为json

2024-05-15 02:27:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有什么帮助吗? 多谢各位


Tags: 对象orgpypijsonlicensemitapachecount
1条回答
网友
1楼 · 发布于 2024-05-15 02:27:17

不需要使用第三方库,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

相关问题 更多 >

    热门问题