如何parsingGolang中嵌套的JSON对象的内部字段?

我有一个类似于这个JSON对象:

{ "name": "Cain", "parents": { "mother" : "Eve", "father" : "Adam" } } 

现在我想parsing“name”和“mother”到这个结构中:

 struct { Name String Mother String `json:"???"` } 

我想用json:... struct标记指定JSON字段名称,但是我不知道如何使用标记,因为它不是我感兴趣的顶级对象。在encoding/json我没有发现任何东西encoding/json软件包文档,也不在stream行的博客文章JSON和GO 。 我还testing了motherparents/motherparents.mother

不幸的是,与encoding/xml不同, json包不提供访问嵌套值的方法。 您将要创build一个单独的Parents结构或将types分配为map[string]string 。 例如:

 type Person struct { Name string Parents map[string]string } 

那么你可以为母亲提供一个吸气剂:

 func (p *Person) Mother() string { return p.Parents["mother"] } 

这可能会也可能不会玩到您当前的代码库中,如果将Mother字段重构为方法调用不在菜单上,那么您可能需要创build一个单独的方法来解码并符合当前的结构。

只要传入的数据不是太dynamic,就可以使用结构。

http://play.golang.org/p/bUZ8l6WgvL

 package main import ( "fmt" "encoding/json" ) type User struct { Name string Parents struct { Mother string Father string } } func main() { encoded := `{ "name": "Cain", "parents": { "mother": "Eve", "father": "Adam" } }` // Decode the json object u := &User{} err := json.Unmarshal([]byte(encoded), &u) if err != nil { panic(err) } // Print out mother and father fmt.Printf("Mother: %s\n", u.Parents.Mother) fmt.Printf("Father: %s\n", u.Parents.Father) } 

这里有一些代码,我在Go游乐场里真正快速地烘烤了

http://play.golang.org/p/PiWwpUbBqt

 package main import ( "fmt" "encoding/json" ) func main() { encoded := `{ "name": "Cain", "parents": { "mother": "Eve" "father": "Adam" } }` // Decode the json object var j map[string]interface{} err := json.Unmarshal([]byte(encoded), &j) if err != nil { panic(err) } // pull out the parents object parents := j["parents"].(map[string]interface{}) // Print out mother and father fmt.Printf("Mother: %s\n", parents["mother"].(string)) fmt.Printf("Father: %s\n", parents["father"].(string)) } 

可能有更好的办法。 我期待着看到其他的答案。 🙂

如何使用中间结构作为parsing,然后把相关的值在你的“真正的”结构?

 import ( "fmt" "encoding/json" ) type MyObject struct{ Name string Mother string } type MyParseObj struct{ Name string Parents struct { Mother string Father string } } func main() { encoded := `{ "name": "Cain", "parents": { "mother": "Eve", "father": "Adam" } }` pj := &MyParseObj{} if err := json.Unmarshal([]byte(encoded), pj); err != nil { return } final := &MyObject{Name: pj.Name, Mother: pj.Parents.Mother} fmt.Println(final) } 

最近, gjson支持select嵌套的JSON属性。

 name := gjson.Get(json, "name") mother := gjson.Get(json, "parents.mother")