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
Penddreth1