我有问题用Go消化一些嵌套的JSON。我的主要问题是我无法正确建模我的结构以尝试让库提取任何信息。以下是JSON数据的示例:http://pastebin.com/fcGQqi5z
这些数据来自银行,并已被删除以保护隐私。理想情况下,我只对交易ID,金额和描述感兴趣。有没有办法用Go来拉这些值?
这是我最初的尝试:
type Trans struct {
TransId string
Amount int
Description string
}
答案 0 :(得分: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)
}
答案 1 :(得分:1)
你在正确的轨道上:
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)
}
//修改
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
}