如何解析嵌套的JSON对象中的内部字段

huangapple go评论127阅读模式
英文:

How to parse an inner field in a nested JSON object

问题

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

现在我想将"name"和"mother"解析到这个结构体中:

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

我想用json:...结构标签指定JSON字段名,但是我不知道该使用什么作为标签,因为我对顶层对象不感兴趣。我在encoding/json包的文档中找不到关于此的任何信息,也没有在流行的博客文章JSON and Go中找到。我还测试了motherparents/motherparents.mother

英文:

I have a JSON object similar to this one:

  1. {
  2. "name": "Cain",
  3. "parents": {
  4. "mother" : "Eve",
  5. "father" : "Adam"
  6. }
  7. }

Now I want to parse "name" and "mother" into this struct:

  1. struct {
  2. Name String
  3. Mother String `json:"???"`
  4. }

I want to specify the JSON field name with the json:... struct tag, however I don't know what to use as tag, because it is not the top object I am interested in. I found nothing about this in the encoding/json package docs nor in the popular blog post JSON and Go. I also tested mother, parents/mother and parents.mother.

答案1

得分: 20

你可以使用结构体,只要你的输入数据不太动态。

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

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. type User struct {
  7. Name string
  8. Parents struct {
  9. Mother string
  10. Father string
  11. }
  12. }
  13. func main() {
  14. encoded := `{
  15. "name": "Cain",
  16. "parents": {
  17. "mother": "Eve",
  18. "father": "Adam"
  19. }
  20. }`
  21. // 解码json对象
  22. u := &User{}
  23. err := json.Unmarshal([]byte(encoded), &u)
  24. if err != nil {
  25. panic(err)
  26. }
  27. // 打印出母亲和父亲
  28. fmt.Printf("Mother: %s\n", u.Parents.Mother)
  29. fmt.Printf("Father: %s\n", u.Parents.Father)
  30. }
英文:

You could use structs so long as your incoming data isn't too dynamic.

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

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. type User struct {
  7. Name string
  8. Parents struct {
  9. Mother string
  10. Father string
  11. }
  12. }
  13. func main() {
  14. encoded := `{
  15. "name": "Cain",
  16. "parents": {
  17. "mother": "Eve",
  18. "father": "Adam"
  19. }
  20. }`
  21. // Decode the json object
  22. u := &User{}
  23. err := json.Unmarshal([]byte(encoded), &u)
  24. if err != nil {
  25. panic(err)
  26. }
  27. // Print out mother and father
  28. fmt.Printf("Mother: %s\n", u.Parents.Mother)
  29. fmt.Printf("Father: %s\n", u.Parents.Father)
  30. }

答案2

得分: 19

不幸的是,与encoding/xml不同,json包没有提供访问嵌套值的方法。您可以创建一个单独的Parents结构体或将类型分配为map[string]string。例如:

  1. type Person struct {
  2. Name string
  3. Parents map[string]string
  4. }

然后,您可以提供一个获取母亲的方法:

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

这可能与您当前的代码库有关,如果将Mother字段重构为方法调用不在计划中,那么您可能需要创建一个单独的方法来进行解码并符合您当前的结构体。

英文:

Unfortunately, unlike encoding/xml, the json package doesn't provide a way to access nested values. You'll want to either create a separate Parents struct or assign the type to be map[string]string. For example:

  1. type Person struct {
  2. Name string
  3. Parents map[string]string
  4. }

You could then provide a getter for mother as so:

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

This may or may not play into your current codebase and if refactoring the Mother field to a method call is not on the menu, then you may want to create a separate method for decoding and conforming to your current struct.

答案3

得分: 6

这是我在Go Playground中快速编写的一些代码

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

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. func main() {
  7. encoded := `{
  8. "name": "Cain",
  9. "parents": {
  10. "mother": "Eve",
  11. "father": "Adam"
  12. }
  13. }`
  14. // 解码json对象
  15. var j map[string]interface{}
  16. err := json.Unmarshal([]byte(encoded), &j)
  17. if err != nil {
  18. panic(err)
  19. }
  20. // 提取出parents对象
  21. parents := j["parents"].(map[string]interface{})
  22. // 打印出母亲和父亲
  23. fmt.Printf("Mother: %s\n", parents["mother"].(string))
  24. fmt.Printf("Father: %s\n", parents["father"].(string))
  25. }

可能有更好的方法。我期待看到其他答案。 如何解析嵌套的JSON对象中的内部字段

英文:

Here's some code I baked up real quick in the Go Playground

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

  1. package main
  2. import (
  3. "fmt"
  4. "encoding/json"
  5. )
  6. func main() {
  7. encoded := `{
  8. "name": "Cain",
  9. "parents": {
  10. "mother": "Eve"
  11. "father": "Adam"
  12. }
  13. }`
  14. // Decode the json object
  15. var j map[string]interface{}
  16. err := json.Unmarshal([]byte(encoded), &j)
  17. if err != nil {
  18. panic(err)
  19. }
  20. // pull out the parents object
  21. parents := j["parents"].(map[string]interface{})
  22. // Print out mother and father
  23. fmt.Printf("Mother: %s\n", parents["mother"].(string))
  24. fmt.Printf("Father: %s\n", parents["father"].(string))
  25. }

There might be a better way. I'm looking forward to seeing the other answers. 如何解析嵌套的JSON对象中的内部字段

答案4

得分: 5

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

  1. name := gjson.Get(json, "name")
  2. mother := gjson.Get(json, "parents.mother")
英文:

More recently, gjson supports selection of nested JSON properties.

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

答案5

得分: 2

如何使用上面建议的中间结构体进行解析,然后将相关的值放入您的“真实”结构体中?

  1. import (
  2. "fmt"
  3. "encoding/json"
  4. )
  5. type MyObject struct{
  6. Name string
  7. Mother string
  8. }
  9. type MyParseObj struct{
  10. Name string
  11. Parents struct {
  12. Mother string
  13. Father string
  14. }
  15. }
  16. func main() {
  17. encoded := `{
  18. "name": "Cain",
  19. "parents": {
  20. "mother": "Eve",
  21. "father": "Adam"
  22. }
  23. }`
  24. pj := &MyParseObj{}
  25. if err := json.Unmarshal([]byte(encoded), pj); err != nil {
  26. return
  27. }
  28. final := &MyObject{Name: pj.Name, Mother: pj.Parents.Mother}
  29. fmt.Println(final)
  30. }
英文:

How about using an intermediary struct as the one suggested above for parsing, and then putting the relevant values in your "real" struct?

  1. import (
  2. "fmt"
  3. "encoding/json"
  4. )
  5. type MyObject struct{
  6. Name string
  7. Mother string
  8. }
  9. type MyParseObj struct{
  10. Name string
  11. Parents struct {
  12. Mother string
  13. Father string
  14. }
  15. }
  16. func main() {
  17. encoded := `{
  18. "name": "Cain",
  19. "parents": {
  20. "mother": "Eve",
  21. "father": "Adam"
  22. }
  23. }`
  24. pj := &MyParseObj{}
  25. if err := json.Unmarshal([]byte(encoded), pj); err != nil {
  26. return
  27. }
  28. final := &MyObject{Name: pj.Name, Mother: pj.Parents.Mother}
  29. fmt.Println(final)
  30. }

huangapple
  • 本文由 发表于 2012年11月28日 05:36:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/13593519.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定