栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python里json和ndJSON 互相转化

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python里json和ndJSON 互相转化

python里json和ndJSON 互相转化
  • 一、 json例子
  • 二、 ndJSON例子
  • 三、 两者区别
  • 四、 ndJSON转json
  • 五、 json转ndJSON
  • 六、若ndJSON是bytes类型

一、 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": "xe4xb8x80"}n{"two": "xe4xbax8c"}n{"three": "xe4xb8x89"}n'
  1. bytes 转 str
    方法一 : str(ndJson, encoding='utf-8')
    方法二 : bytes.decode(ndJson)
  2. str 转 bytes
    方法一 : str.encode(ndJson)
    方法二 : ndJson.encode()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/323642.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号