1

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 } 
2
  • can you post valid json please that can be easily copy/pasted? Commented Oct 3, 2014 at 14:41
  • Updated the pastebin with valid Json Commented Oct 3, 2014 at 14:50

2 Answers 2

1

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\n", data.Record) } 

playground

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

playground

Sign up to request clarification or add additional context in comments.

3 Comments

Since Amount and Description are nested in "AdditionalInfo" how does the parser know to grab it without explicitly telling it that they are located inside "AdditionalInfo" ?
I stand corrected. Just for learning sake, how would I incorporate any details inside "AdditionalInfo"?
@JoshuaGilman I updated the post, basically since AdditionalData has no real format, you can use []map[string]string or []map[string]json.RawMessage.
1
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) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.