【问题标题】:Unmarshalling table-like JSON in Go在 Go 中解组类似表的 JSON
【发布时间】:2021-07-13 15:54:39
【问题描述】:

ElasticSearch 以 JSON 格式的表格结构返回结果(列描述,然后记录为数组)。示例:

{
  "columns" : [
    {
      "name" : "a",
      "type" : "text"
    },
    {
      "name" : "b",
      "type" : "text"
    }
  ],
  "rows" : [
    [
      "a1",
      "b1"
    ],
    [
      "a2",
      "b2"
    ]
  ],
  "cursor" : "Qmd9STC/hM/p3fEF9F7D7FehVn+yLHX4SGVcAB7vk9kGwLjZ4wgfQex4gH+9PuSRmweeHMKtkFiUbTRNFC9bbse4zszAaMv9zKG11aEXQzJzjlRuypdHyDA+RPz66xPVuI1UUkoFpw5EY7k8bFKQ31zhn7x0ie0gv4jGseJJetzXNugw8TwYNR6Id0MVSihm0ogRH9WNFA72CJnqoa26zDPIgXSm/D6QPP40/yXozyAE0gzMnFUYynZf1vlCVdHTQPrCo0TrSMlHvx3BPza5ZnzyLEYZLKULRrTUvtiMOxj+5Ru4izLWSB0jLqeTEkbl5OK9Tyniuq45PeZmZ39UBQ=="
}

是否有最佳实践将其解组为 Go 结构数组(具有有意义的字段名称的结构)。例如:

type Platipus struct {
    A string
    B string
}

【问题讨论】:

    标签: json go elasticsearch unmarshalling


    【解决方案1】:

    这行得通吗?

    package main
    
    import (
       "encoding/json"
       "fmt"
    )
    
    const s = `
    {
       "rows" : [
          ["a1", "b1"], ["a2", "b2"]
       ]
    }
    `
    
    type platipus struct { A, B string }
    
    func (p *platipus) UnmarshalJSON(b []byte) error {
       a := []*string{&p.A, &p.B}
       return json.Unmarshal(b, &a)
    }
    
    func main() {
       var p struct {
          Rows []platipus
       }
       json.Unmarshal([]byte(s), &p)
       fmt.Printf("%+v\n", p.Rows) // [{A:a1 B:b1} {A:a2 B:b2}]
    }
    

    https://golang.org/pkg/encoding/json#RawMessage.UnmarshalJSON

    【讨论】:

      猜你喜欢
      • 2017-07-11
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-16
      • 2020-10-07
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多