python - 将 python dict 转换为 protobuf
问题描述
如何将以下 dict 转换为 protobuf ?
我必须将 protobuf 作为有效负载发送到 mqtt 代理。我正在使用 python 3.8
publish_msg = {
"token":"xxxxxxxx",
"parms":{
"fPort":8,
"data":b"MDQzYzAwMDE=",
"confirmed":False,
"devEUI":"8CF9572000023509"
}
}
我的protobuf定义如下:
syntax = "proto3";
package publish;
message DLParams{
string DevEUI = 1;
int32 FPort = 2;
bytes Data = 3;
bool Confirm = 4;
}
message DeviceDownlink {
string Token = 1;
DLParams Params = 2;
}
解决方案
这个怎么样?
import json
from google.protobuf import json_format
# Create an empty message
dl = DeviceDownlink_pb2.DeviceDownlink()
# Get the json string for your dict
json_string = json.dumps(publish_msg)
# Put the json contents into your message
json_format.Parse(json_string, dl)
推荐阅读
- python - 在 django 视图中写入 Excel 工作表时编码解码问题
- node.js - Debian - 已安装 Nodejs 但未安装 npm
- r - 使用 R Studio 进行聚类分析中相同数据集的不同结果?
- python - Python,MongoDB在开始到结束的范围内聚合
- python - 如何在此代码中实现 TOU 费率?
- tcl - 字符串映射适用于文字但不适用于变量
- docker - "make all -j"$(nproc)" 命令在 Docker 容器中有效,但在 Dockerfile 中无效
- apache-spark - Spark从多列DataFrame批量写入Kafka主题
- java - 将 BitSet 转换为具有相同表示的 byte[]
- php - 以概率选择 RAND()