Gabs是一个小型实用程序,用于处理Go中的动态或未知JSON结构。它不需要您知道有效负载的结构(例如,创建结构),并且可以通过提供指向它们的路径来访问字段。它几乎只是一个有用的包装,用于导航由encoding / json包提供的map [string] interface {}对象的层次结构。除了出色之外,它没有任何壮观的东西。
安装
go get github.com/Jeffail/gabs
例子
package main
import (
"fmt"
"github.com/Jeffail/gabs"
)
func main() {
data := []byte(`{
"employees":{
"protected":false,
"address":{
"street":"22 Saint-Lazare",
"postalCode":"75003",
"city":"Paris",
"countryCode":"FRA",
"country":"France"
},
"employee":[
{
"id":1,
"first_name":"Jeanette",
"last_name":"Penddreth"
},
{
"id":2,
"firstName":"Giavani",
"lastName":"Frediani"
}
]
}
}`)
jsonParsed, err := gabs.ParseJSON(data)
if err != nil {
panic(err)
}
// Search JSON
fmt.Println("Get value of Protected:\t", jsonParsed.Path("employees.protected").Data())
fmt.Println("Get value of Country:\t", jsonParsed.Search("employees", "address", "country").Data())
fmt.Println("ID of first employee:\t", jsonParsed.Path("employees.employee.0.id").String())
fmt.Println("Check Country Exists:\t", jsonParsed.Exists("employees", "address", "countryCode"))
// Iterating address objects
for key, child := range jsonParsed.Search("employees", "address").ChildrenMap() {
fmt.Printf("Key=>%v, Value=>%v\n", key, child.Data().(string))
}
// Iterating employee array
for _, child := range jsonParsed.Search("employees", "employee").Children() {
fmt.Println(child.Data())
}
// Use index in your search
for _, child := range jsonParsed.Search("employees", "employee", "0").Children() {
fmt.Println(child.Data())
}
}
下面的输出。
Get value of Protected: false
Get value of Country: France
ID of first employee: 1
Check Country Exists: true
Key=>street, Value=>22 Saint-Lazare
Key=>postalCode, Value=>75003
Key=>city, Value=>Paris
Key=>countryCode, Value=>FRA
Key=>country, Value=>France
map[id:1 first_name:Jeanette last_name:Penddreth]
map[id:2 firstName:Giavani lastName:Frediani]
Jeanette
Penddreth
1
网友评论