如何将 JSON 数据写入文件? [英] How do I write JSON data to a file?

查看:56
本文介绍了如何将 JSON 数据写入文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 JSON 数据存储在变量 data 中.

I have JSON data stored in the variable data.

我想将其写入文本文件进行测试,这样我就不必每次都从服务器获取数据.

I want to write this to a text file for testing so I don't have to grab the data from the server each time.

目前,我正在尝试:

obj = open('data.txt', 'wb')
obj.write(data)
obj.close

我收到此错误:

TypeError: 必须是字符串或缓冲区,而不是字典

TypeError: must be string or buffer, not dict

如何解决这个问题?

推荐答案

您忘记了实际的 JSON 部分 - data 是一个字典,尚未进行 JSON 编码.编写像这样以获得最大的兼容性(Python 2 和 3):

You forgot the actual JSON part - data is a dictionary and not yet JSON-encoded. Write it like this for maximum compatibility (Python 2 and 3):

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

在现代系统(即 Python 3 和 UTF-8 支持)上,您可以使用

On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file with

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

这篇关于如何将 JSON 数据写入文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆