在python中,我需要将ndjson对象转换为json,我看到pypi.org中有一个库,但是我无法使用它,它是ndjson0.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"
}]有什么帮助吗?谢谢
发布于 2021-05-28 12:32:36
不需要使用第三方库,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) # Truehttps://stackoverflow.com/questions/67736164
复制相似问题