共计 607 个字符,预计需要花费 2 分钟才能阅读完成。
工作中遇到的问题,如何将两个 json 格局的数据合并成同一个,浅记一下,原理就是
- 先将两个 JSON 格局的字符串别离序列化成 []byte
- 而后返序列化到 map[string]interface{}, 实现起映射关系
- 最初序列化该 map, 将序列化的值转换成 string 类型
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
) | |
type S struct { | |
A uint32 `json:"a"` | |
B string `json:"b"` | |
C uint32 `json:"c"` | |
} | |
type S1 struct { | |
B string `json:"b"` | |
C uint32 `json:"c"` | |
D uint32 `json:"d"` | |
} | |
func main() { | |
//json 格局的数据 1 | |
s := S{ | |
A: 12, | |
C: 2, | |
} | |
//json 格局的数据 2 | |
s1 := S1{ | |
B: "123", | |
C: 99999, | |
D: 10, | |
} | |
// 接下来的指标:合并两个 JSON 字符串 | |
js, _ := json.Marshal(s) | |
js1, _ := json.Marshal(s1) | |
var m map[string]interface{} | |
json.Unmarshal(js, &m) | |
json.Unmarshal(js1, &m) | |
fmt.Println(m) | |
res, _ := json.Marshal(m) | |
fmt.Println(string(res)) // {"a":12,"b":"123","c":99999,"d":10} | |
} |
正文完