簡體   English   中英

僅從 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 變量上執行編組后將具有:

{ "persons": [{"id":"1","name":"sun"}, {"id":"2","name":"sam"}] }

我如何提取只是

[{"id":"1","name":"sun"}, {"id":"2","name":"sam"}]

從 buf 沒有清空它??

不確定是否有更好的方法,但不是編組到 json 結構中,而是使用編碼/解碼到 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" ]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM