How to parse an inner field in a nested JSON object

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

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

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

提交回复
热议问题