golang踩坑记录
一.json问题
1.json中存在单引号,json.Unmarshal解析至结构体报错
正常的解析过程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
type ClusterGeneralInfo struct {
InitStatus string `json:"init_status"`
InitTime float64 `json:"init-time"`
}
func TestJsonUnmarshal(t *testing.T) {
ClusterGeneralInfo := ClusterGeneralInfo{}
value := "{'init_status': 'enable', 'init-time': 1638529388.948411}"
//value = `{"init_status": "enable", "init-time": 1638529388.948411}`
err := json.Unmarshal([]byte(value), &ClusterGeneralInfo)
spew.Dump(value)
spew.Dump(ClusterGeneralInfo)
require.NoError(t, err)
}
|
报错
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
=== RUN TestJsonUnmarshal
(string) (len=57) "{'init_status': 'enable', 'init-time': 1638529388.948411}"
(test.ClusterGeneralInfo) {
InitStatus: (string) "",
InitTime: (float64) 0
}
node_test.go:26:
Error Trace: node_test.go:26
Error: Received unexpected error:
invalid character '\'' looking for beginning of object key string
Test: TestJsonUnmarshal
--- FAIL: TestJsonUnmarshal (0.00s)
FAIL
|
json.Unmarshal方法只能解析双引号包裹的标准json,所以做以下处理
1
2
3
4
5
6
7
8
9
10
11
|
func TestJsonUnmarshal(t *testing.T) {
ClusterGeneralInfo := ClusterGeneralInfo{}
value := "{'init_status': 'enable', 'init-time': 1638529388.948411}"
//value = `{"init_status": "enable", "init-time": 1638529388.948411}`
//做替换处理,将单引号替换为双引号
value = strings.Replace(value, "'", "\"", -1)
err := json.Unmarshal([]byte(value), &ClusterGeneralInfo)
spew.Dump(value)
spew.Dump(ClusterGeneralInfo)
require.NoError(t, err)
}
|