如何将JSON数据写入文件

如何将JSON数据写入文件

技术背景

在Python开发中,经常需要将数据以JSON格式存储到文件中,JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,易于人类阅读和编写,同时也易于机器解析和生成。Python提供了json模块来处理JSON数据的编码和解码。

实现步骤

1. 基本写入

1
2
3
4
5
6
7
8
9
10
import json

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

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

2. 提高可读性和优化文件大小

1
2
3
4
5
6
7
8
9
10
import json

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

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

3. 支持Python 2和3及Unicode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# -*- coding: utf-8 -*-
import json
import io

try:
to_unicode = unicode
except NameError:
to_unicode = str

data = {
'a list': [1, 42, 3.141, 1337, 'help', u'€'],
'a string': 'bla',
'another dict': {
'foo': 'bar',
'key': 'value',
'the answer': 42
}
}

with io.open('data.json', 'w', encoding='utf8') as outfile:
str_ = json.dumps(data,
indent=4, sort_keys=True,
separators=(',', ': '), ensure_ascii=False)
outfile.write(to_unicode(str_))

4. 使用mpu

1
2
3
4
import mpu.io

data = mpu.io.read('example.json')
mpu.io.write('example.json', data)

5. 使用pathlib

1
2
3
4
5
6
7
8
9
10
import json
from pathlib import Path

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

Path("data.json").write_text(json.dumps(data))

6. 处理NumPy数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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]),
"int64": np.int64(42)
}

with open('my_filename.json', 'w') as f:
json.dump(my_data, f, indent=4, cls=NumpyEncoder)

7. 使用dummio

1
2
3
4
5
6
7
import dummio

# read
data = dummio.json.load(filepath)

# write
dummio.json.save(data, filepath=filepath)

核心代码

以下是将字典数据写入JSON文件的核心代码:

1
2
3
4
5
6
7
8
9
import json

data = {
"key": "value",
"list": [1, 2, 3]
}

with open('data.json', 'w') as f:
json.dump(data, f, indent=4, ensure_ascii=False)

最佳实践

  • 使用ensure_ascii=Falseindent=4来提高JSON文件的可读性和减小文件大小。
  • 对字典的键进行排序(sort_keys=True),方便使用diff工具比较JSON文件或进行版本控制。
  • 对于包含NumPy数据类型的数据,使用自定义的JSON编码器。

常见问题

1. TypeError: must be unicode, not str

在Python 2中,json.dump()处理包含非ASCII字符的数据时可能会出现此错误。可以使用json.dumps()并手动写入文件,或者使用io.open()并指定encoding='utf-8'

2. TypeError: Object of type 'ndarray' is not JSON serializable

当数据中包含NumPy数组或其他NumPy数据类型时,会出现此错误。可以使用自定义的JSON编码器来解决。

3. is not json serializable

某些自定义对象可能无法直接序列化为JSON。可以为这些对象定义__dict__方法或自定义JSON编码器。


如何将JSON数据写入文件
https://119291.xyz/posts/how-to-write-json-data-to-a-file/
作者
ww
发布于
2025年5月26日
许可协议