json解析go-simplejson的基本使用
// 解析复杂的json
package main
import (
"fmt"
"github.com/bitly/go-simplejson" // for json get
)
// json串 map[string][]slice
var jsonStr = `
{
"person": [{
"name": "piaodd",
"age": 30,
"email": "piaoyunsoft@163.com",
"phoneNum": [
"13974999999",
"13984999999"
]
}, {
"name": "dpq",
"age": 20,
"email": "dpq@163.com",
"phoneNum": [
"13974998888",
"13984998888"
]
}, {
"name": "dpq2",
"age": 10,
"email": "dpq2@163.com",
"phoneNum": [
"13974997777",
"13984997777"
]
}]
}
`
func main() {
js, err := simplejson.NewJson([]byte(jsonStr)) //把需要解析的json填入到Newjson()中
if err != nil {
panic(err.Error())
}
// 获取个人的信息
personArr, err := js.Get("person").Array()
if err != nil {
panic(err.Error())
}
fmt.Println(len(personArr))
fmt.Printf("personArr= %#v \n", personArr)
// 遍历personArr
for i, _ := range personArr {
//fmt.Println(i, v)
person := js.Get("person").GetIndex(i)
// person := js.GetIndex(i).Get("person") 不行
name := person.Get("name").MustString()
age := person.Get("age").MustInt()
email := person.Get("email").MustString()
fmt.Printf("name=%s, age=%d, email=%s\n", name, age, email)
// 读取手机号
phoneNumArr, _ := person.Get("phoneNum").Array()
for ii, vv := range phoneNumArr {
fmt.Println(ii, vv)
}
}
}