golang json字符串合并操作

用于两个json格式的字符串合并,当B向A合并时,共有的字段,将用B字段的值(伴随类型一起覆盖),非共有的,A的字段保留,B的字段新增。

example代码:

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() {
	s := S{
		A: 12,
		C: 2,
	}
	s1 := S1{
		B: "123",
		C: 99999,
		D: 10,
	}
	js, _ := json.Marshal(s)
	js1, _ := json.Marshal(s1)

	var m map[string]interface{}
	json.Unmarshal(js, &m)
	json.Unmarshal(js1, &m)

	res, _ := json.Marshal(m)

	fmt.Println(string(res)) // {"a":12,"b":"123","c":99999,"d":10}
}

  ref:https://stackoverrun.com/cn/q/11154146

猜你喜欢

转载自www.cnblogs.com/bobojiang/p/12620447.html