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

json字符串与python对象互转

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

json字符串与python对象互转

目录

json字符串转python对象

json字符串转dict

 json字符串 转list

python对象转json格式字符串

dict转json

list转json

json格式字符串写入文件

从文件读取json格式字符串


json字符串转python对象

基于json.loads完成

json字符串转dict
    import json

    test_str = '{"name": "ww", "age": 99, "causes": ["A","B"]}'
    json1 = json.loads(test_str)
    print("json1={}, type={}, len(json1)={}".format(json1, type(json1), len(json1)))
    print("json1.age={}".format(json1['age']))
    # json1={'name': 'ww', 'age': 99, 'causes': ['A', 'B']}, type=
    # json1.age=99
    # test_str为正确的json格式

    # test_str2 = "{'name': 'ww', 'age': 99, 'causes': ['A','B']}"
    # json2 = json.loads(test_str2)
    # print("json2={}, type={}".format(json2, type(json2)))
    #  转换失败json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
    #  注意:test_str2字符串不符合json的格式

 json字符串 转list
    test_str1 = ' ["A", "B", "C"]'
    json2 = json.loads(test_str1)
    print("json2={}, type={}, len(json1)={}".format(json2, type(json2), len(json2)))
    print("json2[1]={}".format(json2[1]))
    # json2=['A', 'B', 'C'], type=, len(json1)=3
    # json2[1]=B


python对象转json格式字符串


基于json.dumps完成

dict转json
    dict1 = {'name': 'ww', 'age': 99, 'causes': ['A',"B"]}
    json3 = json.dumps(dict1)
    print("json3={}, type={}".format(json3, type(json3)))
    # json3={"name": "ww", "age": 99, "causes": ["A", "B"]}, type=

list转json
    list1 = ["A", "B", "C"]
    json4 = json.dumps(list1)
    print("json4={}, type={}".format(json4, type(json4)))
    # json4=["A", "B", "C"], type=


json格式字符串写入文件
test_dict = {'name': 'ww', 'age': 99, 'causes': ['A',"B"]}
with open('a.json', 'a', encoding='utf-8') as f0:
    json.dump(test_dict, f0)     
# 参数1传入需要写入文件的字符串对应的python对象即可,无需手动转换为字符串再写入

从文件读取json格式字符串
with open('a.json', 'r', encoding='utf-8') as f0:
    file_data = json.load(f0)


如有帮助,欢迎留下足迹哦!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/965786.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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