- 解析json,xml,结构体
jsonContent :={"name":"john", "score":"100"}
j := gjson.New(jsonContent)
fmt.Println(j.Get(“name”))
jsonContent := <?xml version="1.0" encoding="UTF-8"?><doc><name>john</name><score>100</score></doc>
j := gjson.New(jsonContent)
fmt.Println(j.Get(“doc.name”))
type Me struct {
Name string json:"name"
Score int json:"score"
}
me := Me{
Name: “john”,
Score: 100,
}
j := gjson.New(me)
fmt.Println(j.Get(“name”))
//通过文件读取,支持xml,json
jsonFilePath := gdebug.TestDataPath(“json”, “data1.json”)
j, _ := gjson.Load(jsonFilePath)
//通过字符串
jsonContent := {"name":"john", "score":"100"}
j, _ := gjson.LoadContent(jsonContent)
层级访问
data :=
`{
“users” : {"count" : 2, "list" : [ {"name" : "Ming", "score" : 60}, {"name" : "John", "score" : 99.5} ]
}
}`
j, _ := gjson.DecodeToJson(data)
j.SetViolenceCheck(true) //设置键名带有.的情况读取
fmt.Println(“John Score:”, j.GetFloat32(“users.list.1.score”))
m := j.GetMap(“map”) //获取map
s := j.GetArray(“slice”) //获取scile
//处理list
j, _ := gjson.DecodeToJson(data)
s:=j.GetJsons(“users.list”)
for _,v :=range s{ar:=v.Map() fmt.Println(ar["name"],ar["score"]) ar:=v.GetString("name") //取值 fmt.Println(ar)
}
转换结构体
data :={ "count" : 1, "array" : ["John", "Ming"] }
type Users struct {Count int Array []string
}
users := new(Users)
j,_ := gjson.DecodeToJson(data)
j.Struct(users)
//j.GetStruct(“users”, users) 用于转换某个节点
fmt.Println(users)生成json
j := gjson.New(nil)
for i := 0; i < 2; i++ {//数组
//j.Set(“name”, “John”)
//j.Set(“score”, 99.5)j.Set(fmt.Sprintf(`%d.id`, i), "测试")
}
fmt.Println(j.MustToJsonString())修改或添加
j,_:= gjson.DecodeToJson(data)
j.Set(“users.list.1.score”, 100)
fmt.Println(j.MustToJsonString())
fmt.Println(j.MustToXmlString()) xml
fmt.Println(j.MustToYamlString())
fmt.Println(j.MustToTomlString())
fmt.Println(j.MustToIniString())
j.Set(“users.qq”,nil) 删除
j.Append(“users.list”,2) 添加切片
更新时间:2024-12-05 13:26