\
1{ "code": 1, data: "{ \"itanken.cn\": { \"remain\": 99945, \"success\": 11 }, \"com\": \"result2\", \"zixizixi.cn\": { \"remain\": 99780, \"success\": 44 } }", time: "2021-04-13 20:20:19.123" }
datadata
string(jsonBytes)jsonBytes[]byte[]byte(jsonStr)

反序列化

datadata[]bytedatamap[string]interface{}
1result := make(map[string]interface{})
2
3jsonStr := "{ \"itanken.cn\": { \"remain\": 99945, \"success\": 11 }, \"com\": \"result2\", \"zixizixi.cn\": { \"remain\": 99780, \"success\": 44 } }"
4value := new(map[string]interface{})
5// 反序列化
6err := json.Unmarshal([]byte(jsonStr), &value)
7if err == nil {
8	result["data"] = value
9}
jsonStrdataresultdatadatajsonStrvalueresultjsonStrjsonStrdatadataresultdata/

序列化

resultresult
1// 模拟响应数据到客户端(序列化)
2resultBytes, _ := json.Marshal(result)
3fmt.Println("RESULT:\n", string(resultBytes))

完整示例代码

 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"time"
 7)
 8
 9func main() {
10	jsonStr := `{ "itanken.cn": { "remain": 99945, "success": 11 }, "com": "result2", "zixizixi.cn": { "remain": 99780, "success": 44 } }`
11
12	value := new(map[string]interface{})
13	// 反序列化
14	err := json.Unmarshal([]byte(jsonStr), &value)
15	if err != nil {
16		fmt.Println("JSON 字符串反序列化失败:", err.Error())
17		return
18	}
19	fmt.Println("value:\n", value)
20	// 序列化
21	jsonBytes, _ := json.Marshal(value)
22	fmt.Println("JSON:\n", string(jsonBytes))
23
24	// 结果值
25	result := make(map[string]interface{})
26	result["code"] = 1
27	result["data"] = value // data 必须是一个非序列化值,否则可能会进行二次转义
28	result["time"] = time.Now().UnixNano()
29
30	// 模拟响应数据到客户端(序列化)
31	resultBytes, _ := json.Marshal(result)
32	fmt.Println("RESULT:\n", string(resultBytes))
33}