python 序列化压缩成字符串,如何在Python中将任意文件类型序列化为json字符串

My server is going to be sending a JSON, serialized as a string, through a socket to another client machine. I'll take my final json and do this:

import json

python_dict_obj = { "id" : 1001, "name" : "something", "file" : ??> }

serialized_json_str = json.dumps(python_dict_obj)

I'd like to have one of the fields in my JSON have the value that is a file, encoded as a string.

Performance-wise (but also interoperability-wise) what is the best way to encode a file using python? Base64? Binary? Just the raw string text?

EDIT - For those suggestion base64, something like this?

# get file

import base64

import json

with open(filename, 'r') as f:

filecontents = f.read()

encoded = base64.b64encode(filecontents)

python_dict_obj['file'] = encoded

serialized_json_str = json.dumps(python_dict_obj)

# ... sent to client via socket

# decrpyting

json_again = json.loads(serialized)

filecontents_again = base64.b64decode(json_again['file'])

解决方案

I'd use base64. JSON isn't designed to communicate binary data. So unless your file's content is vanilla text, it "should be" encoded to use vanilla text. Virtually everything can encode and decode base64. If you instead use (for example) Python's repr(file_content), that also produces "plain text", but the receiving end would need to know how to decode the string escapes Python's repr() uses.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值