How to parse an inner field in a nested JSON object

后端 未结 5 1247
一生所求
一生所求 2021-01-31 08:26

I have a JSON object similar to this one:

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

No

5条回答
  •  臣服心动
    2021-01-31 08:56

    You could use structs so long as your incoming data isn't too 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)
    }
    

提交回复
热议问题