【python protobuf序列化】python中如何protobuf与json互相转换
一、protobuf下载安装下载地址:https://github.com/protocolbuffers/protobuf/releases电脑系统是windows10, 下载protoc-3.15.2-win64.zip 解压到相应的目录D:\Program Files下,然后配置环境变量pathD:\Program Files\bin加入path二、新建目录example新建文件openrt
·
一、protobuf下载安装
下载地址:
https://github.com/protocolbuffers/protobuf/releases
电脑系统是windows10, 下载protoc-3.15.2-win64.zip 解压到相应的目录D:\Program Files下,然后配置环境变量path
D:\Program Files\bin 加入path
二、新建目录example
新建文件openrtb.proto 内容如下:
syntax = "proto3";
package proto;
message param {
optional string name = 1;
optional string value = 2;
optional string descibe = 3;
}
下面我们将用命令生成openrtb_pb2.py 文件
cmd 命令 cd 进入example 目录下,
执行如下脚本,直接能够生成openrtb_pb2.py
protoc --python_out=. openrtb.proto
上面步骤做好之后,下面我们需要用python实现基于protobuf协议将json转化为pb string,将pb string转成json
demo 如下:
from example import openrtb_pb2
from google.protobuf import json_format
import json
def pb_to_json(pbStringRequest):
"""将pbstring转化为jsonStringResponse返回"""
jsonStringRequest=json_format.MessageToJson(pbStringRequest)
return jsonStringRequest
def json_to_pb(jsonStringResponse):
"""将jsonStringResponse转化为pbString返回"""
pbStringResponse = json_format.Parse(json.dumps(jsonStringResponse), openrtb_pb2.param())
return pbStringResponse
if __name__ == '__main__':
json_obj={'name':'fcao','value':'0.74','descibe':'202102241339'}
request=json_to_pb(json_obj)
print(request)
print(type(request))
json_result = pb_to_json(request)
print(json_result)
print(type(json_result))
运行结果如下:
name: "fcao"
value: "0.74"
descibe: "202102241339"
<class 'openrtb_pb2.param'>
{
"name": "fcao",
"value": "0.74",
"descibe": "202102241339"
}
<class 'str'>
Process finished with exit code 0
错误解决:
AttributeError: module 'google.protobuf.descriptor' has no attribute '_internal_create_key'
解决办法:
pip install --upgrade protobuf
更多推荐
已为社区贡献13条内容
所有评论(0)