一个简单的问题,我在如何构建用于 JSON 解码的结构时遇到困难。
如何将结构的内部字段复制到结构的另一个字段?
我有 JSON
{
"Trains": [{
"Car": "6",
"Destination": "SilvrSpg",
"DestinationCode": "B08",
"DestinationName": "Silver Spring",
"Group": "1",
"Line": "RD",
"LocationCode": "A13",
"LocationName": "Twinbrook",
"Min": "1"
}]
}
我有结构
type Trains struct {
Min string `json:"Min"`
DestName string `json:"DestinationName"`
DestCode string `json:"DestinationCode"`
LocName string `json:"LocationName"`
LocCode string `json:"LocationCode"`
Line string `json:"Line"`
}
type AllData struct {
Data []Trains `json:"Trains"`
}
如何将 Trains.LocationCode 的值获取到类似这样的结构
type AllData struct {
Id Trains[0].LocCode value
Data []Trains `json:"Trains"`
}
所以我基本上只需要像这样的 JSON
{
"Id":"A13",
"Data": [{
"Car": "6",
"Destination": "SilvrSpg",
"DestinationCode": "B08",
"DestinationName": "Silver Spring",
"Group": "1",
"Line": "RD",
"LocationCode": "A13",
"LocationName": "Twinbrook",
"Min": "1"
}]
}
Id
是 Trains 结构的内部值。
我如何构造一个结构来反射(reflect)这一点?
最佳答案
JSON 解码器没有这个能力。您必须在您的应用程序中编写这行代码。
package main
import (
"encoding/json"
"fmt"
"log"
)
var s = `
{
"Trains": [{
"Car": "6",
"Destination": "SilvrSpg",
"DestinationCode": "B08",
"DestinationName": "Silver Spring",
"Group": "1",
"Line": "RD",
"LocationCode": "A13",
"LocationName": "Twinbrook",
"Min": "1"
}]
}`
type Train struct {
Min string `json:"Min"`
DestName string `json:"DestinationName"`
DestCode string `json:"DestinationCode"`
LocName string `json:"LocationName"`
LocCode string `json:"LocationCode"`
Line string `json:"Line"`
}
type Data struct {
// The name "-" tells the JSON decoder to ignore this field.
ID string `json:"-"`
Trains []Train
}
func main() {
var d Data
if err := json.Unmarshal([]byte(s), &d); err != nil {
log.Fatal(err)
}
if len(d.Trains) < 1 {
log.Fatal("No trains")
}
// Copy value from inner to outer.
d.ID = d.Trains[0].LocCode
fmt.Printf("%+v\n", &d)
}
关于json - 在 Go 中获取内部 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25894352/