我在使用 Go 消化一些嵌套的 JSON 时遇到问题。我的主要问题是我无法正确建模我的结构以尝试让库提取任何信息。这是 JSON 数据的示例:http://pastebin.com/fcGQqi5z
这些数据来自一家银行,并且已经过隐私保护。理想情况下,我只对交易 ID、金额和描述感兴趣。有没有办法用 Go 提取这些值?
这是我最初的尝试:
type Trans struct {
TransId string
Amount int
Description string
}
最佳答案
你走在正确的轨道上:
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
}
关于json - 使用 Go 解析复杂的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26180873/