【问题标题】:converting bytes stream to json using python使用python将字节流转换为json
【发布时间】:2021-05-31 15:31:26
【问题描述】:

我正在开发一个以字节格式向我发送 protobuf 消息的应用程序。 .proto文件的结构如下:

syntax = "proto3";
package api;

message RXInfoSimplified {
    string ID = 1;
    int32 RSSI = 2;
    float SNR = 3;
}

message DeviceUplink {
    string DevEUI = 1;
    int64 ApplicationID = 2;
    string MsgType = 3;
    int64 Timestamp = 4;
    string GatewayID = 5;
    int32 RSSI = 6;
    float SNR = 7;
    float Frequency = 8;
    int32 DataRate = 9;
    bool ADR = 10;
    string Class = 11;
    uint32 FCnt = 12;
    int32 FPort = 13;
    bool Confirm = 14;
    bytes Data = 15;
    repeated RXInfoSimplified Gateways = 16;
}

我必须以 json 格式或 dict 恢复这些消息。我尝试使用 python pickle 和 marshal 模块,但它不起作用。我想知道是否有其他 python 模块或包可以帮助我解决这个问题。 我正在使用 mqtt 从服务器接收有效负载消息。 我的回调函数:

def on_message(client, userdata, msg):
    print(msg.payload)
    print(m)

我得到的字节流:

b'\n\x108cf9572000023509\x10\x03\x1a\x06uplink \xcf\xfb\x84\x99\x9c/*\x10b827ebfffebce2d30\xbd\xff\xff\xff\xff\xff\xff\xff\xff\x01=\x00\x00 AEf\x06YDH\x05P\x01Z\x01C`\x84\x0bh\x08z \x02\x05E!"\x00\x00\x11\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd5\x0e\x00\x82\x01"\n\x10b827ebfffebce2d3\x10\xbd\xff\xff\xff\xff\xff\xff\xff\xff\x01\x1d\x00\x00 A'

【问题讨论】:

  • “它不起作用” - 你必须说明 what 不起作用。
  • 我刚刚编辑了我的问题
  • 我无法将问题中显示的字节流转换为与我的 protobuf 相关的 json。
  • 您可能需要考虑使用由协议缓冲区开发人员工作的同一公司维护的搜索站点搜索 protocol buffers python。跨度>

标签: python json protocol-buffers mqtt


【解决方案1】:

查看 Protobuf 网站上的 Python 教程:

https://developers.google.com/protocol-buffers/docs/pythontutorial

您使用收到的 protobuf 字节流消息的唯一实用方法是将 protobuf 工具用于 - 在您的情况下 - Python(因为这是您正在使用的语言,也是众多语言之一protobuf 工具可用的语言)。

您需要将您在问题中引用的 proto 文件编译成 Python 文件。这个工具叫做protoc

然后您需要将生成的 Python 文件导入到您的代码中。

生成的文件将提供将在线字节流解组为 Python 类的函数,以便您可以在代码中使用它们。

如果您阅读了上面链接的教程,它应该会解释一些细节。

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 2017-02-24
    • 2021-09-09
    • 1970-01-01
    相关资源
    最近更新 更多