golang解析json

1. 需求

获取多级json字符串中的errstr的值

json字符串示例:

1
2
#cat json.txt 
{"app":"test","action":"test.error:app","runtime":1438913605,"server_ip":"1.1.1.1","exe_time":"0.0023","item":{"brief":{"request_api":"testapi","request_params":{"clientid":"11111111","xx":1438913605.964},"client_ip":"0.0.0.0","server_ip":"1.1.1.1"},"detail":{"header":{"code":10006,"info":"info message","desc":"unknown error","record":false},"body":{"errno":8,"errstr":"mysql has gone away","errfile":"/home/data/www/test.php","errline":21}}}}

2. 通过json标准库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main

import (
"encoding/json"
"fmt"
"io/ioutil"
)

var jsonmap map[string]interface{}

func main() {
jsonstr, _ := ioutil.ReadFile("./json.txt")

if err := json.Unmarshal(jsonstr, &jsonmap); err != nil {
fmt.Printf("decode err: %s\n", err)
return
}

item := jsonmap["item"]
itemMap, _ := item.(map[string]interface{})
detail, _ := itemMap["detail"]
detailMap, _ := detail.(map[string]interface{})
body, _ := detailMap["body"]
bodyMap, _ := body.(map[string]interface{})
fmt.Printf("%v\n", bodyMap["errstr"])
}

3. 通过go-simplejson

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package main

import (
"fmt"
"github.com/bitly/go-simplejson"
"io/ioutil"
)


func main() {
jsonstr, _ := ioutil.ReadFile("./json.txt")

sj, err := simplejson.NewJson(jsonstr)
if err != nil {
panic(err)
}
value, _ := sj.Get("item").Get("detail").Get("body").Get("errstr").String()
fmt.Println(value)
}