将我的 json 文件内的数据压缩为二进制

发布于 2025-01-12 09:29:36 字数 463 浏览 4 评论 0原文

我想将 json 文件转换为二进制格式。 example(gzip) 因为我想要数据二进制文件。 当我搜索时,我发现有一种方法可以使用 gzip 来做到这一点。

导入 json import gzip

> def compress_data(data):
>     # Convert to JSON
>     json_data = json.dumps(data, indent=2)
>     # Convert to bytes
>     encoded = json_data.encode('utf-8')
>     # Compress
>     compressed = gzip.compress(encoded)

这对我不起作用,因为我有一个文件而不仅仅是 json 中的对象, 那么,有没有办法将我的文件内的数据压缩为二进制(在 python 中)。 多谢!

I'd like to convert my json file to a binary format. example(gzip) because I want the data binary.
as I searched, I found there is a way to do it with gzip.

import json
import gzip

> def compress_data(data):
>     # Convert to JSON
>     json_data = json.dumps(data, indent=2)
>     # Convert to bytes
>     encoded = json_data.encode('utf-8')
>     # Compress
>     compressed = gzip.compress(encoded)

this didn't work for me as I have a file not just an object in json,
so, is there a way to compress the data inside my file to binary (in python ).
thanks a lot!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷情妓 2025-01-19 09:29:36

看来您的目标是在存储大小方面比较不同的数据表示形式。

其中一种选择是使用 gzip 压缩现有的 json 文件,无论是通过 python 还是直接压缩。请参阅此处如何使用 gzip 模块压缩现有文件 https://docs.python.org/ 3/library/gzip.html

另一种选择是加载 json 文件,然后使用 pickle 模块将其存储为 pickle 文件

with open("file.pkl","wb") as f:
    pickle.dump(obj, f)

It seems your goal is to compare different data representations in terms of storage size.

One of the options is just compressing existing json file with gzip, either through python or directly. See here how to compress existing file with gzip module https://docs.python.org/3/library/gzip.html

Another option is loading json file and then storing is as a pickle file, using pickle module

with open("file.pkl","wb") as f:
    pickle.dump(obj, f)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文