Python中如何将JSON数据写入文件
技术背景
在Python开发中,JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,常用于前后端数据交互、配置文件存储等场景。当我们需要将Python中的字典或列表等数据以JSON格式保存到文件时,就需要掌握如何将JSON数据写入文件的方法。
实现步骤
1. 导入json
模块
Python的json
模块提供了处理JSON数据的功能,我们需要先导入该模块。
2. 准备JSON数据
JSON数据通常以字典或列表的形式存在于Python中。例如:
1 2 3 4 5
| data = { "name": "John", "age": 30, "city": "New York" }
|
3. 打开文件并写入JSON数据
使用open()
函数打开文件,然后使用json.dump()
或json.dumps()
方法将JSON数据写入文件。
使用json.dump()
方法
json.dump()
方法将Python对象直接写入文件对象。
1 2
| with open('data.json', 'w') as f: json.dump(data, f)
|
使用json.dumps()
方法
json.dumps()
方法将Python对象转换为JSON字符串,然后再写入文件。
1 2 3
| json_string = json.dumps(data) with open('data.json', 'w') as f: f.write(json_string)
|
核心代码
以下是一个完整的示例代码,展示了如何将JSON数据写入文件,并对文件进行读取验证:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| import json
data = { "a list": [1, 42, 3.141, 1337, 'help', '€'], "a string": "bla", "another dict": { "foo": "bar", "key": "value", "the answer": 42 } }
with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4)
with open('data.json') as data_file: data_loaded = json.load(data_file)
print(data == data_loaded)
|
最佳实践
提高可读性
为了使生成的JSON文件更易于阅读,可以在json.dump()
或json.dumps()
方法中添加indent
和sort_keys
参数。
1 2
| with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4, sort_keys=True)
|
处理非ASCII字符
如果JSON数据中包含非ASCII字符,建议使用ensure_ascii=False
参数,以避免字符被转义。
1 2
| with open('data.json', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False)
|
常见问题
1. TypeError: must be string or buffer, not dict
当直接将Python字典写入文件时,会出现该错误。因为文件写入操作需要字符串或字节类型的数据,而字典不是字符串类型。解决方法是使用json.dump()
或json.dumps()
方法将字典转换为JSON字符串。
2. 非ASCII字符被转义
如果不使用ensure_ascii=False
参数,非ASCII字符会被转义为Unicode编码。例如:
1 2 3 4
| import json data = {"price": "€10"} print(json.dumps(data)) print(json.dumps(data, ensure_ascii=False))
|
3. 处理NumPy数据类型
如果JSON数据中包含NumPy数据类型,json.dumps()
方法会抛出TypeError
异常。可以自定义一个JSON编码器来处理NumPy数据类型。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| 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)
|