如何在protobuf消息中放入python字典?

tim*_*mer 7 python json protocol-buffers

假设我们有这个Json blob:

{
  "thing": {
    "x": 1,
    "str": "hello,
    "params": {
      "opaque": "yes",
      "unknown": 1,
      "more": ...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

参数的内容未知.我们所知道的只是它是一本字典.我们如何定义可以解析它的protobuf消息?

// file: thing.proto
message Thing {
    uint32 x = 1;
    string str = 2;
    WhatGoesHere? params = 3;
}
Run Code Online (Sandbox Code Playgroud)

[编辑]解决方案:使用谷歌提供的消息.

{
  "thing": {
    "x": 1,
    "str": "hello,
    "params": {
      "opaque": "yes",
      "unknown": 1,
      "more": ...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

tim*_*mer 5

解决方案:使用谷歌提供的消息。

// file: solution.proto
import "google/protobuf/struct.proto";

message Solution1 {
    uint32 x = 1;
    string str = 2;
    google.protobuf.Struct params = 3;
}

message Solution2 {
    uint32 x = 1;
    string str = 2;
    map<string, google.protobuf.Value> params = 3;
}
Run Code Online (Sandbox Code Playgroud)

  • 您不能简单地将字典值分配给 params(解决方案 1) - 它会出错。你必须做 params.update(my_dict) 第二个解决方案缺少一些导入 (2认同)