在Go中获取内部JSON值

时间:2014-09-17 15:15:15

标签: json go

简单的问题是我在如何构建JSON解码结构时遇到了困难。

如何将struct的内部字段复制到struct的另一个字段?

我有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结构的内部值。

如何构建一个结构来反映这个?

1 个答案:

答案 0 :(得分:0)

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)
}