仅从 protobuf 中提取重复的字段元素
Extract just the repeated field elements from protobuf
syntax = "proto3";
package TestServer;
service RelaySrv{
rpc UpdateGroupDetails (Group) returns (Response);
}
message Person
{
int64 id = 1;
string name = 2;
}
message Group{
repeated Person persons = 1;
}
Go code:
var buf bytes.Buffer
m := jsonpb.Marshaler{}
err := m.Marshal(&buf, Group)
对组 protobuf 消息 buf 变量进行编组后将具有:
{ "人员" : [{"id":"1","name":"sun"},
{“id”:“2”,“name”:“sam”}]}
如何只提取
[{"id":"1","name":"sun"},
{“id”:“2”,“name”:“sam”}]
从buf中取出而不清空它??
不确定是否有更好的方法,但不是编组到 json 结构,而是使用 encode/decode 到 json。 ingest.stream 不再抱怨,我可以在 azure-data-explorer
中看到数据
//have a json struct for Group and Person to match the protbuf message posted in the question
var g Group
json.NewDecoder(&buf).Decode(&g)
var b bytes.Buffer
for i := 0; i < len(g.Persons); i++ {
e := json.NewEncoder(&b).Encode(&g.Persons[i])
if e != nil {
panic("issue marshalling protobuf")
}
}
如果我没理解错的话,这就是你想要的。
const b = `[{"id":1,"Name":"sun"}, {"id":2,"Name":"sam"}]`
persons := []*pb.Person{}
err := json.Unmarshal([]byte(b), &persons)
if err != nil {
panic(err.Error())
}
log.Println(persons)
// 2021/03/06 22:34:15 [id:1 name:"sun" id:2 name:"sam" ]
syntax = "proto3";
package TestServer;
service RelaySrv{
rpc UpdateGroupDetails (Group) returns (Response);
}
message Person
{
int64 id = 1;
string name = 2;
}
message Group{
repeated Person persons = 1;
}
Go code:
var buf bytes.Buffer
m := jsonpb.Marshaler{}
err := m.Marshal(&buf, Group)
对组 protobuf 消息 buf 变量进行编组后将具有:
{ "人员" : [{"id":"1","name":"sun"}, {“id”:“2”,“name”:“sam”}]}
如何只提取
[{"id":"1","name":"sun"}, {“id”:“2”,“name”:“sam”}]
从buf中取出而不清空它??
不确定是否有更好的方法,但不是编组到 json 结构,而是使用 encode/decode 到 json。 ingest.stream 不再抱怨,我可以在 azure-data-explorer
中看到数据 //have a json struct for Group and Person to match the protbuf message posted in the question
var g Group
json.NewDecoder(&buf).Decode(&g)
var b bytes.Buffer
for i := 0; i < len(g.Persons); i++ {
e := json.NewEncoder(&b).Encode(&g.Persons[i])
if e != nil {
panic("issue marshalling protobuf")
}
}
如果我没理解错的话,这就是你想要的。
const b = `[{"id":1,"Name":"sun"}, {"id":2,"Name":"sam"}]`
persons := []*pb.Person{}
err := json.Unmarshal([]byte(b), &persons)
if err != nil {
panic(err.Error())
}
log.Println(persons)
// 2021/03/06 22:34:15 [id:1 name:"sun" id:2 name:"sam" ]