Aze*_*der 11 python protocol-buffers
我protoBuffer 3
在其中使用的字段python
未bool
正确显示。
实体原型
message Foo {
string id = 1;
bool active = 3;
}
Run Code Online (Sandbox Code Playgroud)
在 python 中设置值。
foo = entity_proto.Foo(id='id-123', active=True)
print(foo)
# id: id-123
# active: True
# But if you set the value False it does not show 'active' in print statement
foo = entity_proto.Foo(id='id-123', active=False)
print(foo)
# id: id-123
Run Code Online (Sandbox Code Playgroud)
如果您尝试打印print(foo.active)
输出,这False
在某种程度上是可以的。主要问题是当我使用“Http trancoding
如果我尝试打印时console.log(foo.active)
给我undefined
不” false
(lang:JavaScript)
有人可以告诉我为什么它没有显示False
值吗?
Protobuf 有字段的默认值,例如布尔值 false、数字零或空字符串。
它不会对这些进行编码,因为这会浪费空间和/或带宽(在传输时)。这可能就是它没有出现的原因。
检查这一点的一个好方法是将其设置id
为空字符串并查看其行为是否类似:
foo = entity_proto.Foo(id='', active=True)
print(foo)
# active: True (I suspect).
Run Code Online (Sandbox Code Playgroud)
解决方案实际上取决于问题的undefined
来源。Javascript 具有真正的未定义值,在这种情况下您可以使用 null/undefined 合并运算符:
console.log(foo.active ?? false)
Run Code Online (Sandbox Code Playgroud)
或者,如果此 HTTP 转码器正在执行类似创建文字“未定义”字符串之类的操作,则您必须弄清楚如何将(可能的)转换None
为“false”。