Protobuf3:将 Python 对象序列化为 JSON
Protobuf3: Serialize a Python object to JSON
根据the manual,Protobuf 3.0.0 支持JSON序列化:
A well-defined encoding in JSON as an alternative to binary proto encoding.
我尝试了什么
json.dumps(instance)
引发了 TypeError(repr(o) + " is not JSON serializable")
- 寻找
instance.to_json()
(或类似)函数
- 搜索了 Python 文档
如何将 Python 原型对象序列化为 JSON?
json_format
模块中有一个函数MessageToJson
。此函数可用于序列化消息。
注意事项
我错误地安装了 protobuf3
- 我认为它是 protobuf3
Python 包,但它是一个非官方的 Python 3 protobuf 2 包,而不是相反。在开始之前删除它。
解决方案
经过反复试验,以下解决方案有效。如果有更好的/官方的,请随意 post
先决条件:Protobuf 3
- 删除
protobuf2
(我用的是brew uninstall
)。确保 protoc
没有出现在路径中。
- 安装
protobuf3
二进制文件。还没有自制包,所以我使用了 OSX 二进制文件 protoc-3.0.0-osx-x86_64.zip
。 make
脚本也是一个选项。
- 将
bin
目录的内容复制到/usr/local/bin
- 将
include
的内容复制到/usr/local/include
- 确保安装了 protobuf3 -
protoc --version
应该显示 libprotoc 3.0.0
.
Python安装
- 创建虚拟环境
- 下载master branch of
protobuf
到/tmp
- 激活虚拟环境
cd protobuf-master/python && setup.py install
代码
相关函数是MessageToJson
中的google.protobuf.json_format module
:
from google.protobuf import json_format
o = SomeProtobufClass()
print json_format.MessageToJson(o)
{
...
}
根据the manual,Protobuf 3.0.0 支持JSON序列化:
A well-defined encoding in JSON as an alternative to binary proto encoding.
我尝试了什么
json.dumps(instance)
引发了TypeError(repr(o) + " is not JSON serializable")
- 寻找
instance.to_json()
(或类似)函数 - 搜索了 Python 文档
如何将 Python 原型对象序列化为 JSON?
json_format
模块中有一个函数MessageToJson
。此函数可用于序列化消息。
注意事项
我错误地安装了 protobuf3
- 我认为它是 protobuf3
Python 包,但它是一个非官方的 Python 3 protobuf 2 包,而不是相反。在开始之前删除它。
解决方案
经过反复试验,以下解决方案有效。如果有更好的/官方的,请随意 post
先决条件:Protobuf 3
- 删除
protobuf2
(我用的是brew uninstall
)。确保protoc
没有出现在路径中。 - 安装
protobuf3
二进制文件。还没有自制包,所以我使用了 OSX 二进制文件protoc-3.0.0-osx-x86_64.zip
。make
脚本也是一个选项。- 将
bin
目录的内容复制到/usr/local/bin
- 将
include
的内容复制到/usr/local/include
- 将
- 确保安装了 protobuf3 -
protoc --version
应该显示libprotoc 3.0.0
.
Python安装
- 创建虚拟环境
- 下载master branch of
protobuf
到/tmp
- 激活虚拟环境
cd protobuf-master/python && setup.py install
代码
相关函数是MessageToJson
中的google.protobuf.json_format module
:
from google.protobuf import json_format
o = SomeProtobufClass()
print json_format.MessageToJson(o)
{
...
}