How to parse an inner field in a nested JSON object

后端 未结 5 1246
一生所求
一生所求 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:45

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

    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))
    }
    

    There might be a better way. I'm looking forward to seeing the other answers. :-)

提交回复
热议问题