2014-09-17 2 views
0

JSON 디코딩을 위해 구조체를 구조화하는 방법에 어려움을 겪고 있다는 간단한 질문입니다.Go에서 내부 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"` 
} 

나는 그래서 기본적으로

type AllData struct { 
    Id Trains[0].LocCode value 
    Data []Trains `json:"Trains"` 
} 

같은 구조체에 Trains.LocationCode의 가치를 얻을 수있는 방법 이 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 구조체의 내부 값입니다.

어떻게 구조체를 구조화 할 수 있습니까?

+0

나는 당신이하고 싶은 것을 이해하려고 애 쓰고 있습니다. 예제를 단순하게 만들 수 있습니까? – weberc2

답변

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