golang提供了json处理的标准库encoding/json处理,对于结构体,转为json,属性和结构体必须是公有的。
type Stu struct {
ID int `json:"id"`
Sex int `json:"sex"`
Name string `json:"name"`
Number string `json:"number"`
Hobby []string `json:"hobby"`
Addr Address `json:"address"`
}
type Address struct {
AddrName string
Phone string
}
结构体转json。
var stu = Stu{
ID: 1,
Sex: 2,
Name: "小明",
Number: "N123456",
Hobby: []string{"写代码", "足球"},
}
stu.Addr = Address{
AddrName: "test",
Phone: "123456789",
}
//返回的是一个byte类型的切片
stuByte, _ := json.Marshal(stu)
stuJson := string(stuByte)
fmt.Printf("%v\n", stuJson)
json转结构体。
var stuStr = `{"id":1,"sex":2,"name":"小明","number":"N123456","hobby":["写代码","足球"],"address":{"AddrName":"test","Phone":"123456789"}}`
var stuStruct Stu
//应该要修改stuStruct的值,所以需要传入地址
err := json.Unmarshal([]byte(stuStr), &stuStruct)
if err != nil {
fmt.Printf("%v\n", err)
}
fmt.Printf("%#v\n", stuStruct)
还有一些更方便的json处理库,例如
https://github.com/tidwall/gjson
嵌套json字符串的提取。
var json = `{"name":{"first":"Janet","last":"Prichard"},"age":47}`
last := gjson.Get(json, "name.last")
age := gjson.Get(json, "age")
fmt.Printf("last=%v,last-type=%T\n", last.String(), last.String())
fmt.Printf("age=%v,age-type=%T\n", age.Int(), age.Int())
聚合计算
jsonData := `{
"products": [
{"name": "苹果", "money": 11},
{"name": "香蕉", "money": 1},
{"name": "橘子", "money": 1},
]
}`
result := gjson.Get(jsonData, "products.#(money < 2)")
cheapProducts := result.Array()
fmt.Println("便宜的水果:", cheapProducts)