有没有办法将`json.dump`和`gzip`一起使用? [英] Is there a way to use `json.dump` with `gzip`?

查看:124
本文介绍了有没有办法将`json.dump`和`gzip`一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处是一个关于如何使用json.dumps写入gzip文件的绝佳答案.我想做的是使用dump方法,而不是直接将json序列化为GzipFile对象.

Here is a great answer about how to use json.dumps to write to a gzip file. What I would like to do is to use the dump method instead to serialize the json directly into a GzipFile object.

示例代码:

import gzip, json

data = # a dictionary of data here
with gzip.open(write_file, 'w') as zipfile:
   json.dump(data, zipfile)

引发的错误是

TypeError: memoryview: a bytes-like objet is required, not 'str'

我认为这是由于gzip write()方法想要将字节对象传递给它而引起的.根据文档

I believe this is caused because the gzip write() method wants a bytes object passed to it. Per the documentation,

json模块始终生成str对象,而不生成byte对象. 因此,fp.write()必须支持str输入.

The json module always produces str objects, not bytes objects. Therefore, fp.write() must support str input.

是否有一种方法可以将json字符串输出包装为字节,以便GzipFilewrite()可以处理?还是唯一的方法是像其他链接的答案一样,将json.dumpsencode()生成的字符串用作字节对象?

Is there a way to wrap the json string output as bytes so that GzipFile's write() will handle it? Or is the only way to do this to use json.dumps and encode() the resulting string into a bytes object, as in the other linked answer?

推荐答案

gzip模块提供了开箱即用的支持:只需声明一种编码,它将unicode字符串编码为字节,然后再将其写入文件:

The gzip module supports it out of the box: just declare an encoding and it will encode the unicode string to bytes before writing it to the file:

with gzip.open(write_file, 'wt', encoding="ascii") as zipfile:
   json.dump(data, zipfile)

确保使用文本模式('wt')指定.

Make sure you specify using text mode ('wt').

由于json已经对任何非ascii字符进行了编码,所以ascii编码就足够了,但是对于前128个代码点,您可以使用与ascii兼容的任何其他编码,例如Latin1,UTF-8等

As json has encoded any non ascii character, ascii encoding is enough, but you could any other encoding compatible with ascii for the first 128 code points like Latin1, UTF-8, etc

这篇关于有没有办法将`json.dump`和`gzip`一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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