python里json和ndJSON 互相转化

一、 json例子

[
    {"one": "一"},
    {"two": "二"},
    {"three": "三"},
]

二、 ndJSON例子

{"one": "一"}
{"two": "二"}
{"three": "三"}

三、 两者区别

区别:上面两个例子数据使用了不同的序列化格式,数据所表达的含义也是不同的。json例子只表达了一个对象:一个列表,ndJSON例子则表达了3个对象:3个字典。

注意的点:ndJSON里对象后面使用了换行符 \n

参考链接:https://jimmy.blog.csdn.net/article/details/100915601?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-4.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-4.no_search_link

四、 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类型

  1. 例子
# 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'
  1. bytes 转 str
    方法一 : str(ndJson, encoding='utf-8')
    方法二 : bytes.decode(ndJson)
  2. str 转 bytes
    方法一 : str.encode(ndJson)
    方法二 : ndJson.encode()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值