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

查看:1258
本文介绍了如何将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: 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天全站免登陆