Go 处理 Json 有比较优雅的方式吗?结构体好麻烦

2021-11-17 02:23:27 +08:00
 szxczyc

通过请求体:{"tags":["baidu"],"item_id":8}得到了一个 json 的返回值:

{
    "data": {
        "baidu": {
            "sdus": [
                {
                    "sdu_name": "hello-redis-live",
                    "service_id": 12,
                    "owners": [
                        "132@123.com"
                    ],
                    "sdu_id": 17,
                    "service": "tech.cto.redis"
                },
                {
                    "sdu_name": "good-worker-live",
                    "service_id": 10,
                    "owners": [
                        "132@123.com"
                    ],
                    "sdu_id": 159,
                    "service": "tech.cto.retoc.worker"
                }
            ]
        }
    },
    "error": 0
}

其中,tags 的值baidu的请求,导致每次返回的 Json 里baidu会随之改变。

我用 go 该怎么样才能只取"sdu_name""service"呢?

json.unmarshall 没办法处理~

我尝试构造了几次结构体,但是只要 tags:baidu一变化,请求体就没办法处理了~

type Service struct {
	Data  Data  `json:"data"` 
	Error int64 `json:"error"`
}

type Data struct {
	Baidu Baidu `json:"baidu"`
}

type Baidu struct {
	Sdus []Sdus `json:"sdus"`
}

type Sdus struct {
	SduName   string   `json:"sdu_name"`  
	ServiceID int64    `json:"service_id"`
	Owners    []string `json:"owners"`    
	SduID     int64    `json:"sdu_id"`    
	Service   string   `json:"service"`   
}

1525 次点击
所在节点    问与答
8 条回复
Buges
2021-11-17 02:34:46 +08:00
你是说返回的 data.baidu 字段名是动态的,其他结构不变?
那把 Data 改成 map[string]Baidu
szxczyc
2021-11-17 03:11:11 +08:00
@Buges 我只能说一声牛逼~可以了卧槽~
szxczyc
2021-11-17 03:19:09 +08:00
@Buges 感谢大佬。我已经拿到了这样的结构。
```json
{
"data":{
"baidu":{
"sdus":[
{
"sdu_name":"hello-redis-live",
"service":"tech.cto.redis"
},
{
"sdu_name":"good-worker-live",
"service":"tech.cto.retoc.worker"
}
]
}
}
}
```
另外想问一下,如果我想只拿出里面这样的结构,是可以做的吗?
```json
{
"sdus":[
{
"sdu_name":"hello-redis-live",
"service":"tech.cto.redis"
},
{
"sdu_name":"good-worker-live",
"service":"tech.cto.retoc.worker"
}
]
}
```
iyear
2021-11-17 07:48:56 +08:00
@szxczyc 然后遍历 map 不就拿到了吗
yianing
2021-11-17 08:31:15 +08:00
考虑下 gjson 或者 sonic ,自带 json 库功能比较弱
TypeError
2021-11-17 09:40:10 +08:00
goland 自带支持复制粘贴 json 后转换成结构体
jazzychai
2021-11-17 12:29:47 +08:00
szxczyc
2021-11-17 14:22:48 +08:00
不知道 gjson 的[] result 结构怎么转换

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/815905

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX