如何将JSON数据写入文件?

本文翻译自:How do I write JSON data to a file?

I have JSON data stored in the variable data . 我将JSON数据存储在变量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. 我想将其写入文本文件进行测试,因此不必每次都从服务器获取数据。

Currently, I am trying this: 目前,我正在尝试:

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

And am receiving the error: 并收到错误:

TypeError: must be string or buffer, not dict

How to fix this? 如何解决这个问题?

#1楼

参考:https://stackoom.com/question/peCb/如何将JSON数据写入文件

#2楼

You forgot the actual JSON part – data is a dictionary and not yet JSON-encoded. 您忘记了实际的JSON部分- data是一个字典,尚未进行JSON编码。 Write it like this for maximum compatibility (Python 2 and 3): 这样的最大兼容性(Python 2和3):

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

On a modern system (ie Python 3 and UTF-8 support), you can write a nicer file with 在现代系统(即Python 3和UTF-8支持)上,您可以使用

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

#3楼

To get utf8 -encoded file as opposed to ascii -encoded in the accepted answer for Python 2 use: 要获取utf8 编码的文件,而不是Python 2可接受答案中的ascii 编码 ,请使用:

import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
  f.write(json.dumps(data, ensure_ascii=False))

The code is simpler in Python 3: 该代码在Python 3中更简单:

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

On Windows, the encoding='utf-8' argument to open is still necessary. 在Windows上,仍然需要open encoding='utf-8'参数。

To avoid storing an encoded copy of the data in memory (result of dumps ) and to output utf8-encoded bytestrings in both Python 2 and 3, use: 为避免将数据的编码副本存储在内存中( dumps结果),并在Python 2和3中输出utf8编码的字节串,请使用:

import json, codecs
with open('data.txt', 'wb') as f:
    json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)

The codecs.getwriter call is redundant in Python 3 but required for Python 2 codecs.getwriter调用在Python 3中是多余的,但对于Python 2是必需的

Readability and size: 可读性和大小:

The use of ensure_ascii=False gives better readability and smaller size: 使用ensure_ascii=False可提供更好的可读性和更小的尺寸:

>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'

>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17

Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66 ) to arguments of dump or dumps . 通过添加标志进一步提高可读性indent=4, sort_keys=True (如通过建议dinos66 )至参数dumpdumps This way you’ll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size. 这样,您将在json文件中获得一个很好的缩进排序结构,但要付出稍大的文件大小。

#4楼

I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. 我会稍作修改,对上述答案进行回答,那就是编写一个美化的JSON文件,人眼可以更好地阅读。 For this, pass sort_keys as True and indent with 4 space characters and you are good to go. 为此,将sort_keys传递为Trueindent 4个空格字符,您就可以使用了。 Also take care of ensuring that the ascii codes will not be written in your JSON file: 还要注意确保不会将ASCII代码写入您的JSON文件中:

with open('data.txt', 'w') as outfile:
     json.dump(jsonData, outfile, sort_keys = True, indent = 4,
               ensure_ascii = False)

#5楼

For those of you who are trying to dump greek or other “exotic” languages such as me but are also having problems (unicode errors) with weird characters such as the peace symbol (\) or others which are often contained in json formated data such as Twitter’s, the solution could be as follows (sort_keys is obviously optional): 对于那些尝试转储希腊语或其他“异类”语言(例如我)但也遇到奇怪字符(例如和平符号(\\ u262E)或通常包含在json格式数据中的其他字符)的问题(unicode错误)的人例如Twitter,解决方案可能如下(sort_keys显然是可选的):

import codecs, json
with codecs.open('data.json', 'w', 'utf8') as f:
     f.write(json.dumps(data, sort_keys = True, ensure_ascii=False))

#6楼

Write a data in file using JSON use json.dump() or json.dumps() used. 使用JSON使用json.dump()json.dumps()在文件中写入数据。 write like this to store data in file. 这样写即可将数据存储在文件中。

import json
data = [1,2,3,4,5]
with open('no.txt', 'w') as txtfile:
    json.dump(data, txtfile)

this example in list is store to a file. 列表中的此示例存储到文件中。

    原文作者:p15097962069
    原文地址: https://blog.csdn.net/p15097962069/article/details/105313363
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞