Python 将 json 数据写入 .json 文件中(json 中包含中文)

  • 正常导入

    # 解析 json
    import json
    
    # 读取
    accounts = json.load(open('./accounts.json', 'r', encoding="utf-8"))
    
    # 修改内容
    account = accounts[0]
    account['result'] = 1
    
    # 存入
    with open('./accounts.json', 'r+', encoding='utf-8') as f:
      # 方式一:
      json.dump(accounts, f, indent=4)
      # 方式二:
      # f.write(json.dumps(accounts, indent=4))
    
  • 如果 json 中有中文,存入文件后显示的 unicode 编码,但是需要显示成中文

    # 解析 json
    import json
    
    # json
    info = {
        '订单需求信息': {'订单任务编号':'','观测目标名称':'','观测目标经度':''},
        '任务规划结果': {'子订单任务编号':'','观测目标名称':''},   
    }
    
    # 存入
    with open('./accounts.json', 'r+', encoding='utf-8') as f:
      # 方式一:
      json.dumps(info, f, indent=4, ensure_ascii=False)
      # 方式二:
      # f.write(json.dumps(accounts, indent=4, ensure_ascii=False))
    
    • 一定用 json.dumps()dumps 是将 dict 转化成 str 格式,否则报错。json.dumps() 可以将该 python 字典转换成字符串类型,返回 json 字符串。

    • indent=4 缩进 4

    • json.dumps() 序列化时对中文默认使用的 ascii 编码,想输出真正的中文需要指定 ensure_ascii=False

  • 常用方法

    • json.dumps() 把数据类型转换成字符串

    • json.dump() 把数据类型转换成字符串并存储在文件中

    • json.loads() 把字符串转换成数据类型

    • json.load() 把文件打开从字符串转换成数据类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

卡尔特斯

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

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

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

打赏作者

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

抵扣说明:

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

余额充值