Documentation ¶
Overview ¶
Package gjson provides searching for json strings.
Package match provides a simple pattern matcher with unicode support.
Index ¶
- Variables
- func AddModifier(name string, fn func(json, arg string) string)
- func Allowable(pattern string) (min, max string)
- func AppendJSONString(dst []byte, s string) []byte
- func Color(src []byte, style *Style) []byte
- func Escape(comp string) string
- func ForEachLine(json string, iterator func(line Result) bool)
- func IsPattern(str string) bool
- func Match(str, pattern string) bool
- func MatchLimit(str, pattern string, maxcomp int) (matched, stopped bool)
- func ModifierExists(name string, fn func(json, arg string) string) bool
- func Pretty(json []byte) []byte
- func PrettyOptions(json []byte, opts *Options) []byte
- func Spec(src []byte) []byte
- func SpecInPlace(src []byte) []byte
- func Ugly(json []byte) []byte
- func UglyInPlace(json []byte) []byte
- func Valid(json string) bool
- func ValidBytes(json []byte) bool
- type Options
- type Result
- func (t Result) Array() []Result
- func (t Result) Bool() bool
- func (t Result) Exists() bool
- func (t Result) Float() float64
- func (t Result) ForEach(iterator func(key, value Result) bool)
- func (t Result) Get(path string) Result
- func (t Result) Int() int64
- func (t Result) IsArray() bool
- func (t Result) IsBool() bool
- func (t Result) IsObject() bool
- func (t Result) Less(token Result, caseSensitive bool) bool
- func (t Result) Map() map[string]Result
- func (t Result) Path(json string) string
- func (t Result) Paths(json string) []string
- func (t Result) String() string
- func (t Result) Time() time.Time
- func (t Result) Uint() uint64
- func (t Result) Value() interface{}
- type Style
- type Type
Constants ¶
This section is empty.
Variables ¶
var DefaultOptions = &Options{Width: 80, Prefix: "", Indent: " ", SortKeys: false}
DefaultOptions is the default options for pretty formats.
var DisableModifiers = false
DisableModifiers will disable the modifier syntax
Functions ¶
func AddModifier ¶
AddModifier binds a custom modifier command to the GJSON syntax. This operation is not thread safe and should be executed prior to using all other gjson function.
func Allowable ¶
Allowable parses the pattern and determines the minimum and maximum allowable values that the pattern can represent. When the max cannot be determined, 'true' will be returned for infinite.
func AppendJSONString ¶
AppendJSONString is a convenience function that converts the provided string to a valid JSON string and appends it to dst.
func Color ¶
Color will colorize the json. The style parma is used for customizing the colors. Passing nil to the style param will use the default TerminalStyle.
func Escape ¶
Escape returns an escaped path component.
json := `{ "user":{ "first.name": "Janet", "last.name": "Prichard" } }` user := gjson.Get(json, "user") println(user.Get(gjson.Escape("first.name")) println(user.Get(gjson.Escape("last.name")) // Output: // Janet // Prichard
func ForEachLine ¶
ForEachLine iterates through lines of JSON as specified by the JSON Lines format (http://jsonlines.org/). Each line is returned as a GJSON Result.
func Match ¶
Match returns true if str matches pattern. This is a very simple wildcard match where '*' matches on any number characters and '?' matches on any one character.
pattern:
{ term }
term:
'*' matches any sequence of non-Separator characters '?' matches any single non-Separator character c matches character c (c != '*', '?', '\\') '\\' c matches character c
func MatchLimit ¶
MatchLimit is the same as Match but will limit the complexity of the match operation. This is to avoid long running matches, specifically to avoid ReDos attacks from arbritary inputs.
How it works: The underlying match routine is recursive and may call itself when it encounters a sandwiched wildcard pattern, such as: `user:*:name`. Everytime it calls itself a counter is incremented. The operation is stopped when counter > maxcomp*len(str).
func ModifierExists ¶
ModifierExists returns true when the specified modifier exists.
func Pretty ¶
Pretty converts the input json into a more human readable format where each element is on it's own line with clear indentation.
func PrettyOptions ¶
PrettyOptions is like Pretty but with customized options.
func Spec ¶
Spec strips out comments and trailing commas and convert the input to a valid JSON per the official spec: https://tools.ietf.org/html/rfc8259
The resulting JSON will always be the same length as the input and it will include all of the same line breaks at matching offsets. This is to ensure the result can be later processed by a external parser and that that parser will report messages or errors with the correct offsets.
func SpecInPlace ¶
SpecInPlace is the same as Spec, but this method reuses the input json buffer to avoid allocations. Do not use the original bytes slice upon return.
func Ugly ¶
Ugly removes insignificant space characters from the input json byte slice and returns the compacted result.
func UglyInPlace ¶
UglyInPlace removes insignificant space characters from the input json byte slice and returns the compacted result. This method reuses the input json buffer to avoid allocations. Do not use the original bytes slice upon return.
func Valid ¶
Valid returns true if the input is valid json.
if !gjson.Valid(json) { return errors.New("invalid json") } value := gjson.Get(json, "name.last")
func ValidBytes ¶
ValidBytes returns true if the input is valid json.
if !gjson.Valid(json) { return errors.New("invalid json") } value := gjson.Get(json, "name.last")
If working with bytes, this method preferred over ValidBytes(string(data))
Types ¶
type Options ¶
type Options struct { // Width is an max column width for single line arrays // Default is 80 Width int // Prefix is a prefix for all lines // Default is an empty string Prefix string // Indent is the nested indentation // Default is two spaces Indent string // SortKeys will sort the keys alphabetically // Default is false SortKeys bool }
Options is Pretty options
type Result ¶
type Result struct { // Type is the json type Type Type // Raw is the raw json Raw string // Str is the json string Str string // Num is the json number Num float64 // Index of raw value in original json, zero means index unknown Index int // Indexes of all the elements that match on a path containing the '#' // query character. Indexes []int }
Result represents a json value that is returned from Get().
func Get ¶
Get searches json for the specified path. A path is in dot syntax, such as "name.last" or "age". When the value is found it's returned immediately.
A path is a series of keys separated by a dot. A key may contain special wildcard characters '*' and '?'. To access an array value use the index as the key. To get the number of elements in an array or to access a child path, use the '#' character. The dot and wildcard character can be escaped with '\'.
{ "name": {"first": "Tom", "last": "Anderson"}, "age":37, "children": ["Sara","Alex","Jack"], "friends": [ {"first": "James", "last": "Murphy"}, {"first": "Roger", "last": "Craig"} ] } "name.last" >> "Anderson" "age" >> 37 "children" >> ["Sara","Alex","Jack"] "children.#" >> 3 "children.1" >> "Alex" "child*.2" >> "Jack" "c?ildren.0" >> "Sara" "friends.#.first" >> ["James","Roger"]
This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. If you are consuming JSON from an unpredictable source then you may want to use the Valid function first.
func GetBytes ¶
GetBytes searches json for the specified path. If working with bytes, this method preferred over Get(string(data), path)
func GetMany ¶
GetMany searches json for the multiple paths. The return value is a Result array where the number of items will be equal to the number of input paths.
func GetManyBytes ¶
GetManyBytes searches json for the multiple paths. The return value is a Result array where the number of items will be equal to the number of input paths.
func Parse ¶
Parse parses the json and returns a result.
This function expects that the json is well-formed, and does not validate. Invalid json will not panic, but it may return back unexpected results. If you are consuming JSON from an unpredictable source then you may want to use the Valid function first.
func ParseBytes ¶
ParseBytes parses the json and returns a result. If working with bytes, this method preferred over Parse(string(data))
func (Result) Array ¶
Array returns back an array of values. If the result represents a null value or is non-existent, then an empty array will be returned. If the result is not a JSON array, the return value will be an array containing one result.
func (Result) Exists ¶
Exists returns true if value exists.
if gjson.Get(json, "name.last").Exists(){ println("value exists") }
func (Result) ForEach ¶
ForEach iterates through values. If the result represents a non-existent value, then no values will be iterated. If the result is an Object, the iterator will pass the key and value of each item. If the result is an Array, the iterator will only pass the value of each item. If the result is not a JSON array or object, the iterator will pass back one value equal to the result.
func (Result) Get ¶
Get searches result for the specified path. The result should be a JSON array or object.
func (Result) Less ¶
Less return true if a token is less than another token. The caseSensitive parameter is used when the tokens are Strings. The order when comparing two different type is:
Null < False < Number < String < True < JSON
func (Result) Map ¶
Map returns back a map of values. The result should be a JSON object. If the result is not a JSON object, the return value will be an empty map.
func (Result) Path ¶
Path returns the original GJSON path for a Result where the Result came from a simple path that returns a single value, like:
gjson.Get(json, "friends.#(last=Murphy)")
The returned value will be in the form of a JSON string:
"friends.0"
The param 'json' must be the original JSON used when calling Get.
Returns an empty string if the paths cannot be determined, which can happen when the Result came from a path that contained a multipath, modifier, or a nested query.
func (Result) Paths ¶
Paths returns the original GJSON paths for a Result where the Result came from a simple query path that returns an array, like:
gjson.Get(json, "friends.#.first")
The returned value will be in the form of a JSON array:
["friends.0.first","friends.1.first","friends.2.first"]
The param 'json' must be the original JSON used when calling Get.
Returns an empty string if the paths cannot be determined, which can happen when the Result came from a path that contained a multipath, modifier, or a nested query.
type Style ¶
type Style struct {
Key, String, Number [2]string
True, False, Null [2]string
Escape [2]string
Brackets [2]string
Append func(dst []byte, c byte) []byte
}
Style is the color style
var TerminalStyle *Style
TerminalStyle is for terminals