如何在Golang中分析嵌套JSON对象中的内部字段? [英] How do I parse an inner field in a nested JSON object in Golang?

查看:705
本文介绍了如何在Golang中分析嵌套JSON对象中的内部字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与此类似的JSON对象:

  {
name:Cain,
父母:{
mother:Eve,
father:Adam
}
}

$ p
$ b

现在我想将name和mother解析到这个结构中:

  struct {
名称字符串
母串`json:???``
}

我想用 json:... struct标签指定JSON字段名称,但是我不知道如何使用标签,因为它不是我感兴趣的顶级对象。在 encoding / json 软件包文档也不在流行的博客文章 JSON和Go 。我还测试了母亲父母/母亲 parents.mother

解决方案

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

 类型Person结构{
名称字符串
父母map [string]字符串
}

然后,您可以为母亲提供一个getter:

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

这可能会也可能不会影响您当前的代码库,如果重构 Mother 字段到方法调用不在菜单上,那么您可能需要创建一个单独的方法来解码并符合当前的结构。


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.

这篇关于如何在Golang中分析嵌套JSON对象中的内部字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆