python爬虫中json数据与python数据相互转换

        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)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱笑的蛐蛐

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值