json类型数据:

  • 数据以键值对的形式存在(且必须使用双引号括起来):如  "name": "张三"
  • 使用 {} 包含多个键值对,使用逗号分割:{"name": "张三", "age": 18}

1. json数据转换成python数据

        1.1 json字符串转换成python字符串

  • 使用 json.loads(json数据) 进行转换,返回的结果是列表或字典的数据类型
import json
jso = """[{"provinceName":"台湾","provinceShortName":"台湾","currentConfirmedCount":4823386,
"confirmedCount":4846501,"suspectedCount":485,"curedCount":13742,"deadCount":9373,"comment":"",
"locationId":710000,"statisticsData":"https://file1.dxycdn.com/2020/0223/045/3398299749526003760-135.json",
"highDangerCount":0,"midDangerCount":0,"detectOrgCount":0,"vaccinationOrgCount":0,
"cities":[],"dangerAreas":[]}]"""
# 1.把json字符串转换成python字符串(即列表嵌套字典)
# 1.1转换
rs = json.loads(jso)
print(rs)

        1.2 json文件转换成python数据类型

  • 使用 json.load(json文件名) 进行转换,返回的结果是列表或字典的数据类型
# 2.把json文件格式转换成python文件格式
# 2.1 构建指向该文件的文件对象
with open('1.json', 'r') as f:
    # 2.2 加载文件对象,转换成python类型数据
    python_list = json.load(f)
    print(python_list)

2.  python数据类型转换成json数据类型

       2.1 python字符串转换成json字符串

  •  使用 json.dumps(python数据,ensure_ascii=False),返回json数据类型
import json
# 1.把python字符串转换成json字符串
list1 = """[{'provinceName': '台湾', 'provinceShortName': '台湾',
 'currentConfirmedCount': 4823386, 'confirmedCount': 4846501, 'suspectedCount': 485,
  'curedCount': 13742, 'deadCount': 9373, 'comment': '', 'locationId': 710000, 
  'statisticsData': 'https://file1.dxycdn.com/2020/0223/045/3398299749526003760-135.json', 
  'highDangerCount': 0, 'midDangerCount': 0, 'detectOrgCount': 0, 'vaccinationOrgCount': 0, 
  'cities': [], 'dangerAreas': []}]"""
# 1.1 python转换成json
python_list = json.dumps(list1, ensure_ascii=False)  # 指定编码
print(python_list)

        2.2 python数据以json格式存储在磁盘中

  • 使用 json.dump(python数据, 文件名, ensure_ascii=False)
# 把python文件以json格式存储在磁盘中
with open('2.json', 'w') as f:
    # ensure_ascii 可以改变编码方式
    json.dump(list1, f, ensure_ascii=False)

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐