在 python 中将 ndjson 转换为 json
convert ndjson to json in 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"
}]
有什么帮助吗?
谢谢
不用第三方库,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
我需要在 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