英文:
Parsing complex JSON with Go
问题
我在使用Go语言处理一些嵌套的JSON时遇到了问题。我的主要问题是无法正确建模我的结构体,以便尝试从库中提取任何信息。这是JSON数据的示例:http://pastebin.com/fcGQqi5z
这些数据来自一家银行,并已经进行了隐私处理。理想情况下,我只对交易ID、金额和描述感兴趣。有没有办法使用Go语言只提取这些值?
这是我的初始尝试:
type Trans struct {
TransId string
Amount int
Description string
}
英文:
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
}
答案1
得分: 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)
}
希望对您有所帮助!
英文:
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)
}
答案2
得分: 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)
}
//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](http://play.golang.org/p/PP_aFbWCkL)
英文:
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)
}
//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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论