在 Go 中解组 table-like JSON
Unmarshalling table-like JSON in Go
ElasticSearch returns 在 JSON 中产生类似 table 的结构(列描述,然后记录为数组)。示例:
{
"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
}
这个有用吗?
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
ElasticSearch returns 在 JSON 中产生类似 table 的结构(列描述,然后记录为数组)。示例:
{
"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
}
这个有用吗?
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