且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-01-12 10:54:06

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

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

您可以这样为母亲提供吸气剂:

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

这可能会或可能不会影响当前的代码库,并且如果菜单上未包含将Mother字段重构为方法调用的内容,那么您可能希望创建一个单独的方法来解码并符合当前的结构. /p>

I have a JSON object similar to this one:

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

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

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

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.

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.