python里json和ndJSON 互相转化
一、 json例子
[
{"one": "一"},
{"two": "二"},
{"three": "三"},
]
二、 ndJSON例子
{"one": "一"}
{"two": "二"}
{"three": "三"}
三、 两者区别
区别:上面两个例子数据使用了不同的序列化格式,数据所表达的含义也是不同的。json例子只表达了一个对象:一个列表,ndJSON例子则表达了3个对象:3个字典。
注意的点:ndJSON里对象后面使用了换行符 \n
四、 ndJSON转json
ndJson = '{"one": "一"}\n{"two": "二"}\n{"three": "三"}\n'
def ndJson_to_json(ndJson):
ndJson = ndJson.split('\n')
if len(ndJson) > 0:
if ndJson[-1] == '':
ndJson = ndJson[:-1]
return [json.loads(i) for i in ndJson]
return []
result = ndJson_to_json(ndJson)
print(result)
结果:
[{'one': '一'}, {'two': '二'}, {'three': '三'}]
五、 json转ndJSON
json_data = [{"one": "一"}, {"two": "二"}, {"three": "三"}]
def json_to_ndJson(json_data):
ndJson = ''
for j in json_data:
ndJson += json.dumps(j, ensure_ascii=False) + '\n'
return ndJson
print(json_to_ndJson(json_data))
结果:
{"one": "一"}
{"two": "二"}
{"three": "三"}
六、若ndJSON是bytes类型
- 例子
# str
ndJson = '{"one": "一"}\n{"two": "二"}\n{"three": "三"}\n'
# bytes
ndJSON = b'{"one": "\xe4\xb8\x80"}\n{"two": "\xe4\xba\x8c"}\n{"three": "\xe4\xb8\x89"}\n'
- bytes 转 str
方法一 :str(ndJson, encoding='utf-8')
方法二 :bytes.decode(ndJson)
- str 转 bytes
方法一 :str.encode(ndJson)
方法二 :ndJson.encode()