Github address of the project
Searcher
The Searcher module provides golang with easy json field access, and the interface will be as simple and easy to use as possible
Quick start
The installation
$ go get github.com/markity/searcher
Copy the code
usage
Given json data
var jsonString = ` { "name":"Markity", "age":"16", "friends":[ { "name":"Jack", "age":17 }, { "name":"Mary", "age":18, "email":"[email protected]" } ], "details":{ "interests":["golang","python"] } } `
Copy the code
Create a searcher using JSON data
import "github.com/markity/searcher"
// If json data is invalid, error is not nil
s, err := searcher.New([]byte(jsonString))
iferr ! =nil {
fmt.Printf("invalid json data: %v", err)
return
}
Copy the code
Get field values
// Get a field. The parameter must be of type int or string
result := s.Query("friends".0."name")
// Check whether the field exists
if! result.Exists() { fmt.Println("the result does not exists")
return
}
// You can determine the type of field. The types include TypeNumber, TypeBool, TypeString, TypeArray, TypeObject, and TypeNull
ifresult.Type ! = searcher.TypeString { fmt.Println("wrong type of the field")
return
}
GetInt64, GetUint64, GetFloat64, GetBool, GetString, GetObject, GetArray, GetValue)
// Before using the GetXXX method, you must determine its type (using the wrong "Get method "will cause panic).
For example, if result.Type is TypeNumber, you can use GetInt64, GetUint64 and GetFloat64
fmt.Printf("My first friend's name is %s\n", result.GetString())
Copy the code