我需要在 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"
}]
有什么帮助吗?
谢谢
无需使用第三方库,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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)