Golang:通过 FieldMask 过滤 Protobuf Struct 字段

问题描述 投票:0回答:1

我有一个 protobuf 结构存储我的任意 json。我需要使用 fmutils

根据提供的字段掩码路径列表过滤并仅保留一些字段

但是,它似乎不适用于结构类型,因为我的所有字段都消失了(我的结构变为空)。代码如下。我还需要做点别的吗?

package main

import (
    structpb "github.com/golang/protobuf/ptypes/struct"
    "google.golang.org/protobuf/encoding/protojson"
    "github.com/mennanov/fmutils"
)

func main() {
    jsonString := `{
                        "field_a": true,
                        "field_b": {
                            "sub_field_b": 99
                        }
                    }`

    myPbStruct := &structpb.Struct{}
    protojson.Unmarshal([]byte(jsonString), myPbStruct)

    fmutils.Filter(myPbStruct, []string{"field_a"})
    // myPbStruct becomes empty after this step
}

go protocol-buffers
1个回答
0
投票

我不熟悉

fmutils

Struct
定义为
fields: map<string,Value
,其中
Value

因此,您需要在过滤器前添加

fields
来过滤
Value
的:

package main

import (
    structpb "github.com/golang/protobuf/ptypes/struct"
    "github.com/mennanov/fmutils"
    "google.golang.org/protobuf/encoding/protojson"
)

func main() {
    jsonString := `{
                        "field_a": true,
                        "field_b": {
                            "sub_field_b": 99
                        }
                    }`

    myPbStruct := &structpb.Struct{}
    protojson.Unmarshal([]byte(jsonString), myPbStruct)

    fmutils.Filter(myPbStruct, []string{"fields.field_a"})
    // myPbStruct becomes empty after this step
}
© www.soinside.com 2019 - 2024. All rights reserved.