How to parse an inner field in a nested JSON object

后端 未结 5 1237
一生所求
一生所求 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 09:02

    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:

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

    You could then provide a getter for mother as so:

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

    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.

提交回复
热议问题