Golang用DYNAMIC键解析一个json [英] Golang parse a json with DYNAMIC key

查看:133
本文介绍了Golang用DYNAMIC键解析一个json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个json字符串,如下所示:

  j:=`{bvu62fu6dq:{
姓名:约翰,
年龄:23,
xyz:weu33s
.....
.....}
}`

我想提取 name age 来自json字符串。我查看了golang站点 http://play.golang.org/p/YQgzP7KPp9 给出的示例



但是我的问题是关于顶层json的关键是动态的。这意味着 bvu62fu6dq 是动态的。

 类型信息结构{
UniqueID map [string] string
}

但不知道如何提取名称年龄。我的代码位于 http://play.golang.org/p/Vbdkd3XIKc


<我相信你想要的东西是这样的:

  type Person struct {
名称字符串`json:name`
年龄int`json:age`
}

类型Info map [string] Person

然后,在解码完成后:

<$ p $年龄)
fmt.Printf(%s:%d \ n,info [bvu62fu6dq]。Name,info [bvu62fu6dq]。 c>

完整示例: http://play.golang.org/p/FyH-cDp3Na


I have a json string as follows:

j := `{"bvu62fu6dq": {
           "name": "john",
           "age": 23,
           "xyz": "weu33s"
           .....
           .....}
      }`

I want to extract the value of name and age from above json string. I looked at this example given at golang site http://play.golang.org/p/YQgzP7KPp9

But my problem is the key in the json on top level is dynamic. That means bvu62fu6dq is dynamic. I have created struct like this:

 type Info struct {
   UniqueID map[string]string
 }

But not sure how to extract name and age. My code is at http://play.golang.org/p/Vbdkd3XIKc

解决方案

I believe you want something like this:

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

type Info map[string]Person

Then, after decoding this works:

fmt.Printf("%s: %d\n", info["bvu62fu6dq"].Name, info["bvu62fu6dq"].Age)

Full example: http://play.golang.org/p/FyH-cDp3Na

这篇关于Golang用DYNAMIC键解析一个json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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