lol*_*ter 9 python serialization json
我的服务器将发送一个JSON,序列化为字符串,通过套接字发送到另一台客户端机器.我会拿最后的json做这个:
import json
python_dict_obj = { "id" : 1001, "name" : "something", "file" : <???> }
serialized_json_str = json.dumps(python_dict_obj)
Run Code Online (Sandbox Code Playgroud)
我想让我的JSON中的一个字段具有作为文件的值,编码为字符串.
性能方面(但也是互操作性)使用python编码文件的最佳方法是什么?Base64编码?二进制?只是原始的字符串文本?
编辑 - 对于那些建议base64,这样的事情?
# 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'])
Run Code Online (Sandbox Code Playgroud)
我用了base64.JSON不是为了传递二进制数据而设计的.因此,除非您的文件内容是香草文本,否则它应"编码"以使用香草文本.事实上,一切都可以编码和解码base64.如果您改为使用(例如)Python repr(file_content),那么也会产生"纯文本",但接收端需要知道如何解码Python repr()使用的字符串转义.
| 归档时间: |
|
| 查看次数: |
7971 次 |
| 最近记录: |