I'm having issues digesting some nested JSON with Go. My primary issue is that I can't model my struct correctly to try and get the library to pull any information in. Here is a sample of the JSON data: http://pastebin.com/fcGQqi5z
The data is from a bank and has been scrubbed for privacy. Ideally I'm only interested in the transactions ID, the amount, and the description. Is there a way to just pull these values with Go?
This was my initial attempt:
type Trans struct {
TransId string
Amount int
Description string
}
You were on the right tracks:
type Trans struct {
TransId string
Amount float64
Description string
}
func main() {
var data struct {
Record []Trans
}
if err := json.Unmarshal([]byte(j), &data); err != nil {
fmt.Println(err)
return
}
fmt.Printf("%#v
", data.Record)
}
//edit
type Trans struct {
TransId string
Amount float64
Description string
RawInfo []map[string]json.RawMessage `json:"AdditionalInfo"`
}
// also this assumes that 1. all data are strings and 2. they have unique keys
// if this isn't the case, you can use map[string][]string or something
func (t *Trans) AdditionalInfo() (m map[string]string) {
m = make(map[string]string, len(t.RawInfo))
for _, info := range t.RawInfo {
for k, v := range info {
m[k] = string(v)
}
}
return
}
type Records struct {
Records []Record `json:"record"`
}
type Record struct {
TransId string
Amount float64
Description string
}
func main() {
r := Records{}
if err := json.Unmarshal([]byte(data), &r); err != nil {
log.Fatal(err)
}
fmt.Println(r)
}