Go语言JSON库:Jason
jopen
10年前
Jason目标是成为Go语言开发中惯用的JSON库。受其它库的启发并对一些常见的使用进行了改进,它当前专注于读取JSON数据,但不创建JSON。
数据类型
下面golang值用于JSON数据类型。及与原始数据类型的对应关系:
bool
, for JSON booleansfloat64
, for JSON numbersstring
, for JSON strings[]*Jason
, for JSON arraysmap[string]*Jason
, for JSON objectsnil
for JSON null
示例代码:
root, err := jason.NewFromReader(res.Body) root.Get("name").String() root.Get("age").Number() root.Get("verified").Boolean() root.Get("education").Object() root.Get("friends").Array() //读取嵌套内容 root.Get("person", "name").String() root.Get("person", "age").Number() root.Get("person", "verified").Boolean() root.Get("person", "education").Object() root.Get("person", "friends").Array() //判断数值是否存在 root.Has("person", "name") root.Get("person", "name").Exists() //数值校验 root.Get("name").IsString() root.Get("age").IsNumber() root.Get("verified").IsBoolean() root.Get("education").IsObject() root.Get("friends").IsArray() root.Get("friends").IsNull() //循环 for _, friend := range person.Get("friends").Array() { name := friend.Get("name").String() age := friend.Get("age").Number() }
完整例子:
package main import ( "github.com/antonholmquist/jason" "log" ) func main() { exampleJSON := `{ "name": "Walter White", "age": 51, "children": [ "junior", "holly" ], "other": { "occupation": "chemist", "years": 23 } }` j, _ := jason.NewFromString(exampleJSON) log.Println("name:", j.Get("name").String()) log.Println("age:", j.Get("age").Number()) log.Println("occupation:", j.Get("other", "occupation").String()) log.Println("years:", j.Get("other", "years").Number()) for i, child := range j.Get("children").Array() { log.Printf("child %d: %s", i, child.String()) } }