如何在 go 中展平嵌套的 json 结构

Nag*_*hab 7 go bson

我从 mongo 获取嵌套数据,我想将其展平到一个结构中以将其存储在 csv 文件中。

数据如下:

{
    "_id" : "bec7bfaa-7a47-4f61-a463-5966a2b5c8ce",
    "data" : {
        "driver" : {
            "etaToStore" : 156
        },
        "createdAt" : 1532590052,
        "_id" : "07703a33-a3c3-4ad5-9e06-d05063474d8c"
    }
} 
Run Code Online (Sandbox Code Playgroud)

我想要最终得到的结构应该是这样的

type EventStruct struct {
    Id                  string      `bson:"_id"`
    DataId              string      `bson:"data._id"`
    EtaToStore          string      `bson:"data.driver.etaToStore"`
    CreatedAt           int         `bson:"data.createdAt"`
}
Run Code Online (Sandbox Code Playgroud)

这是行不通的,所以根据一些 SO 答案,我将其分解为多个结构:

// Creating a structure for the inner struct that I will receive from the query
type DriverStruct struct {
    EtaToStore  int     `bson:"etaToStore"`
}

type DataStruct struct {
    Id          string `bson:"_id"`
    Driver      DriverStruct `bson:"driver"`
    CreatedAt   int `bson:"createdAt"`
}
// Flattenning out the structure & getting the fields we need only
type EventStruct struct {
    Id                  string      `bson:"_id"`
    Data                DataStruct  `bson:"data"`
}
Run Code Online (Sandbox Code Playgroud)

这会从 Mongo 查询结果中获取所有数据,但它是嵌套的:

{
  "Id": "bec7bfaa-7a47-4f61-a463-5966a2b5c8ce",
  "Data": {
     "Id": a33-a3c3-4ad5-9e06-d05063474d8c,
     "Driver": {
        "EtaToStore": 156
     },
     "CreatedAt": 1532590052
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要的最终结果是:

{
  "Id": "bec7bfaa-7a47-4f61-a463-5966a2b5c8ce",
  "DataId": "a33-a3c3-4ad5-9e06-d05063474d8c",
  "EtaToStore": 156,
  "CreatedAt": 1532590052
}
Run Code Online (Sandbox Code Playgroud)

我确信有一个简单的方法可以做到这一点,但我无法弄清楚,救命!

Zak*_*Zak 6

您可以实现该json.Unmarshaler接口以添加自定义方法来解组 json。然后在该方法中,您可以使用嵌套结构格式,但在最后返回扁平结构。

func (es *EventStruct) UnmarshalJSON(data []byte) error {
    // define private models for the data format

    type driverInner struct {
        EtaToStore int `bson:"etaToStore"`
    }

    type dataInner struct {
        ID        string      `bson:"_id" json:"_id"`
        Driver    driverInner `bson:"driver"`
        CreatedAt int         `bson:"createdAt"`
    }

    type nestedEvent struct {
        ID   string    `bson:"_id"`
        Data dataInner `bson:"data"`
    }

    var ne nestedEvent

    if err := json.Unmarshal(data, &ne); err != nil {
        return err
    }

    // create the struct in desired format
    tmp := &EventStruct{
        ID:         ne.ID,
        DataID:     ne.Data.ID,
        EtaToStore: ne.Data.Driver.EtaToStore,
        CreatedAt:  ne.Data.CreatedAt,
    }

    // reassign the method receiver pointer
    // to store the values in the struct
    *es = *tmp
    return nil
}
Run Code Online (Sandbox Code Playgroud)

可运行示例: https: //play.golang.org/p/83VHShfE5rI


Wug*_*Wug 6

这个问题已经有一年半的历史了,但是我今天在对 API 更新做出反应时遇到了这个问题,这使我处于同样的情况,所以这是我的解决方案(诚然,我还没有测试过bson,但我假设jsonbson字段标签阅读器实现以相同的方式处理它们)

嵌入式(有时称为匿名)字段可以捕获 JSON,因此您可以将多个结构组合成一个复合结构,其行为类似于单个结构。

{
    "_id" : "bec7bfaa-7a47-4f61-a463-5966a2b5c8ce",
    "data" : {
        "driver" : {
            "etaToStore" : 156
        },
        "createdAt" : 1532590052,
        "_id" : "07703a33-a3c3-4ad5-9e06-d05063474d8c"
    }
} 
Run Code Online (Sandbox Code Playgroud)
type DriverStruct struct {
    EtaToStore          string      `bson:"etaToStore"`

type DataStruct struct {
    DriverStruct                    `bson:"driver"`
    DataId              string      `bson:"_id"`
    CreatedAt           int         `bson:"createdAt"`
}

type EventStruct struct {
    DataStruct                      `bson:"data"`
    Id                  string      `bson:"_id"`
}
Run Code Online (Sandbox Code Playgroud)

您可以访问嵌入结构的嵌套字段,就像父结构包含等效字段一样,因此例如EventStructInstance.EtaToStore是获取它们的有效方法。

好处:

  • 您不必实现MarshallerorUnmarshaller接口,这对于这个问题来说有点矫枉过正
  • 不需要在中间结构之间复制任何字段
  • 免费处理编组和解组

在此处阅读有关嵌入字段的更多信息。