【问题标题】:Google Protocol Buffers List of Lists PythonGoogle Protocol Buffers 列表 Python 列表
【发布时间】:2021-02-22 09:00:42
【问题描述】:

您好,我有一个关于 json 中列表列表的协议缓冲区的问题:

示例 .json (testjson)

"outcome": {
    "col": [
        "datetime",
        "return"
    ],
    "val": [[1199232000000, -0.0066], [1199318400000, -0.0033]]
}

我的 .proto 文件 (cum_ret.proto)

message CumReturn {
  
  message period_value {
    oneof types{
      int32 day = 1;
      float return = 2;
    }
  }
  message period_values {
    repeated period_value value = 1;
  }

  message outcome {
    repeated string col = 1;
    repeated period_value val = 2;
  }

  outcome outcome_returns = 2;
}

我使用以下代码解析 json:

testjson = {
    "outcome_returns": {
        "col": [
            "datetime",
            "cum_returns"
        ],
        "val": [[1199232000000, -0.0066705691], [1199318400000, -0.0033641154]]
    }
}
 
import cum_ret_pb2 as CumRet 
from google.protobuf.json_format import Parse
cumrets = Parse(json.dumps(test_json), CumRet.CumReturn())

但我收到了错误消息:

Failed to parse 1199232000000 field: expected string or bytes-like object...

有人可以帮忙:获取一个 int 列表并浮动到 .proto 架构中吗?

【问题讨论】:

    标签: python json list parsing protocol-buffers


    【解决方案1】:

    实现列表列表的一种方法是为您的列表创建一条新消息:

    message ListOfInt {
      repeated int32 value = 1;
    }
    

    当你调用它时,使用

      message outcome {
        repeated string col = 1;
        repeated ListOfInt val = 2;
      }
    

    但是,我认为您的代码中存在不同的问题。您的“period_value”消息需要一个 int32 或一个浮点数。最大 int32 值为 2,147,483,647,但您试图将 1,199,232,000,000 放入该字段。因此,无法解析该值的错误消息。尝试将 int32 更改为 int64:

    message period_value {
        oneof types {
          int64 day = 1;
          float return = 2;
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-15
      • 2011-05-06
      • 1970-01-01
      • 2022-10-25
      相关资源
      最近更新 更多