转换JSON消息的最佳实践



假设我有一条JSON消息,如下所示:

{
"aaaa": 14,
"bbbb": "",
"cccc": {
"c1": 121,
"needed": [
{
"_c21": 22.25972,
"_c22": {
"needed1": "123",
"needed2": "test"
}
},
{
"_c21": 22.25972,
"_c22": {
"needed1": "123",
"needed2": "test"
}
},
{
"_c21": 22.25972,
"_c22": {
"needed1": "123",
"needed2": "test"
}
}
]
}
}

如何将其转换为类似的内容

{
"needed": [{
"needed1": "123",
"needed2": "test"
}, {
"needed1": "123",
"needed2": "test"
}, {
"needed1": "123",
"needed2": "test"
}
]
}

在这种情况下,我认为只需要迭代来检索needed1needed2的组件。我也在想,对于Golang来说,处理零和空的最佳做法是什么?(与Java中一样,在处理数据之前,建议先使用if条件检查每个密钥(

下面的代码应该能满足您的需求:

package main
import (
"encoding/json"
"fmt"
)
var input = `{
"aaaa": 142,
"bbbb": "",
"cccc": {
"c1": 121,
"needed": [
{
"_c21": 22.25972,
"_c22": {
"needed1": "123",
"needed2": "test"
}
},
{
"_c21": 22.25972,
"_c22": {
"needed1": "123",
"needed2": "test"
}
},
{
"_c21": 22.25972,
"_c22": {
"needed1": "123",
"needed2": "test"
}
}
]
}
}`
type Json struct {
Cccc struct {
NeededList []struct {
C22 needed `json:"_c22"`
} `json:"needed"`
}`json:"cccc"`
}
type needed struct {
Needed1 string `json:"needed1"`
Needed2 string `json:"needed2"`
}
func main() {
j := &Json{}
json.Unmarshal([]byte(input), j)
result := make([]needed, 0)
for _, n := range j.Cccc.NeededList {
result = append(result, n.C22)
}
out, _ := json.Marshal(result)
fmt.Println(string(out))
}

相关内容

  • 没有找到相关文章

最新更新