当前位置: 代码网 > it编程>前端脚本>Python > Python中将JSON数据写入文件的实现方法

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

2025年06月25日 Python 我要评论
python中如何将json数据写入文件技术背景在python开发中,json(javascript object notation)是一种轻量级的数据交换格式,常用于前后端数据交互、配置文件存储等场

python中如何将json数据写入文件

技术背景

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

实现步骤

1. 导入json模块

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

import json

2. 准备json数据

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

data = {
    "name": "john",
    "age": 30,
    "city": "new york"
}

3. 打开文件并写入json数据

使用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)

处理非ascii字符

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

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编码。例如:

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

3. 处理numpy数据类型

如果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数据写入文件内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com