Python中将JSON数据写入文件的实现方法

Written by

in

文章目录
  • 目录
    • Python中如何将JSON数据写入文件
      • 技术背景
      • 实现步骤
        • 1. 导入json模块
        • 2. 准备JSON数据
        • 3. 打开文件并写入JSON数据
      • 核心代码
        • 最佳实践
          • 提高可读性
          • 处理非ASCII字符
        • 常见问题
          • 1. TypeError: must be string or buffer, not dict
          • 2. 非ASCII字符被转义
          • 3. 处理NumPy数据类型

      在Python开发中,JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据交互、配置文件存储等场景。当我们需要将Python中的字典或列表等数据以JSON格式保存到文件时,就需要掌握如何将JSON数据写入文件的方法。

      Python的json模块提供了处理JSON数据的功能,我们需要先导入该模块。

      import json
      

      JSON数据通常以字典或列表的形式存在于Python中。例如:

      data = {
          "name": "John",
          "age": 30,
          "city": "New York"
      }
      

      使用open()函数打开文件,然后使用json.dump()json.dumps()方法将JSON数据写入文件。

      使用json.dump()方法

      json.dump()方法将Python对象直接写入文件对象。

      with open('data.json', 'w') as f:
          json.dump(data, f)
      

      使用json.dumps()方法

      json.dumps()方法将Python对象转换为JSON字符串,然后再写入文件。

      json_string = json.dumps(data)
      with open('data.json', 'w') as f:
          f.write(json_string)
      

      以下是一个完整的示例代码,展示了如何将JSON数据写入文件,并对文件进行读取验证:

      import json
      
      # 准备JSON数据
      data = {
          "a list": [1, 42, 3.141, 1337, 'help', '€'],
          "a string": "bla",
          "another dict": {
              "foo": "bar",
              "key": "value",
              "the answer": 42
          }
      }
      
      # 写入JSON文件
      with open('data.json', 'w', encoding='utf-8') as f:
          json.dump(data, f, ensure_ascii=False, indent=4)
      
      # 读取JSON文件
      with open('data.json') as data_file:
          data_loaded = json.load(data_file)
      
      print(data == data_loaded)
      

      为了使生成的JSON文件更易于阅读,可以在json.dump()json.dumps()方法中添加indentsort_keys参数。

      with open('data.json', 'w', encoding='utf-8') as f:
          json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
      

      如果JSON数据中包含非ASCII字符,建议使用ensure_ascii=False参数,以避免字符被转义。

      with open('data.json', 'w', encoding='utf-8') as f:
          json.dump(data, f, ensure_ascii=False)
      

      当直接将Python字典写入文件时,会出现该错误。因为文件写入操作需要字符串或字节类型的数据,而字典不是字符串类型。解决方法是使用json.dump()json.dumps()方法将字典转换为JSON字符串。

      如果不使用ensure_ascii=False参数,非ASCII字符会被转义为Unicode编码。例如:

      import json
      data = {"price": "€10"}
      print(json.dumps(data))  # 输出: '{"price": "\u20ac10"}'
      print(json.dumps(data, ensure_ascii=False))  # 输出: '{"price": "€10"}'
      

      如果JSON数据中包含NumPy数据类型,json.dumps()方法会抛出TypeError异常。可以自定义一个JSON编码器来处理NumPy数据类型。

      import json
      import numpy as np
      
      class NumpyEncoder(json.JSONEncoder):
          """ Special json encoder for np types """
          def default(self, obj):
              if isinstance(obj, (np.int_, np.intc, np.intp, np.int8,
                                  np.int16, np.int32, np.int64, np.uint8,
                                  np.uint16, np.uint32, np.uint64)):
                  return int(obj)
              elif isinstance(obj, (np.float_, np.float16, np.float32,
                                    np.float64)):
                  return float(obj)
              elif isinstance(obj, (np.ndarray,)):
                  return obj.tolist()
              return json.JSONEncoder.default(self, obj)
      
      my_data = {'array': np.array([1, 2, 3])}
      with open('my_filename.json', 'w') as f:
          json.dump(my_data, f, indent=4, cls=NumpyEncoder)
      

      到此这篇关于Python中将JSON数据写入文件的实现方法的文章就介绍到这了,更多相关Python将JSON数据写入文件内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

      您可能感兴趣的文章:

      • 使用Python将JSON,XML和YAML数据写入Excel文件
      • Python使用json模块读取和写入JSON数据
      • 使用Python读取和写入JSON文件的代码示例
      • Python读取和写入txt、Excel文件和JSON文件的方法
      • Python实现将字典内容写入json文件

      站内搜索