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

163 阅读1分钟
  • 正常导入

    # 解析 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() 把文件打开从字符串转换成数据类型