Import path:
gitlab.soludian.com/soludian/fountain/libs/base/fson
fson
import "gitlab.soludian.com/soludian/fountain/libs/base/fson"Index
- Variables
- func AddModifier(name string, fn func(json, arg string) string)
- func AppendJSONString(dst []byte, s string) []byte
- func Color(src []byte, style *Style) []byte
- func Delete(json, path string) (string, error)
- func DeleteBytes(json []byte, path string) ([]byte, error)
- func Escape(comp string) string
- func ForEachLine(json string, iterator func(line Result) bool)
- func JSONBytes(obj any) []byte
- func JSONDebugData(message any) []byte
- func JSONDebugDataString(message any) string
- func JSONString(obj any) string
- func JSONUnEscape(obj any) string
- func JSONUnEscapeBytes(obj any) []byte
- func ModifierExists(name string, fn func(json, arg string) string) bool
- func Pretty(json []byte) []byte
- func PrettyEscapeJSONBytes(obj any) []byte
- func PrettyJSON(obj any) string
- func PrettyJSONBytes(obj any) []byte
- func PrettyOptions(json []byte, opts *OptionsPretty) []byte
- func PrettyUnEscapeJSON(obj any) string
- func ProtoBinaryBytes(m proto.Message) []byte
- func ProtoBinaryString(m proto.Message) string
- func ProtoJSONBytes(m proto.Message) []byte
- func ProtoJSONString(m proto.Message) string
- func ReadFile(filePath string, v any) error
- func Set(json, path string, value any) (string, error)
- func SetBytes(json []byte, path string, value any) ([]byte, error)
- func SetBytesOptions(json []byte, path string, value any, opts *OptionsSet) ([]byte, error)
- func SetOptions(json, path string, value any, opts *OptionsSet) (string, error)
- func SetRaw(json, path, value string) (string, error)
- func SetRawBytes(json []byte, path string, value []byte) ([]byte, error)
- func SetRawBytesOptions(json []byte, path string, value []byte, opts *OptionsSet) ([]byte, error)
- func SetRawOptions(json, path, value string, opts *OptionsSet) (string, error)
- func Spec(src []byte) []byte
- func SpecInPlace(src []byte) []byte
- func StripComments(src string) string
- func Ugly(json []byte) []byte
- func UglyInPlace(json []byte) []byte
- func UnmarshalBinary(data []byte, m proto.Message) error
- func UnmarshalJSON(data []byte, m proto.Message) error
- func Valid(json string) bool
- func ValidBytes(json []byte) bool
- func WriteFile(filePath string, data any) error
- func WritePretty(filePath string, data any) error
- type OptionsPretty
- type OptionsSet
- type Result
- func Get(json, path string) Result
- func GetBytes(json []byte, path string) Result
- func GetMany(json string, path ...string) []Result
- func GetManyBytes(json []byte, path ...string) []Result
- func Parse(json string) Result
- func ParseBytes(json []byte) 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() any
- type Style
- type Type
Variables
DisableModifiers will disable the modifier syntax
var DisableModifiers = falsevar OmitDefaultAPI = jsoniter.Config{
SortMapKeys: true,
UseNumber: true,
CaseSensitive: true,
EscapeHTML: true,
ValidateJsonRawMessage: true,
}.Froze()PrettyDefaultOptions is the default options for pretty formats.
var PrettyDefaultOptions = &OptionsPretty{Width: 80, Prefix: "", Indent: " ", SortKeys: false}func AddModifier
func AddModifier(name string, fn func(json, arg string) string)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 AppendJSONString
func AppendJSONString(dst []byte, s string) []byteAppendJSONString is a convenience function that converts the provided string to a valid JSON string and appends it to dst.
func Color
func Color(src []byte, style *Style) []byteColor 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 Delete
func Delete(json, path string) (string, error)Delete deletes a value from json for the specified path.
func DeleteBytes
func DeleteBytes(json []byte, path string) ([]byte, error)DeleteBytes deletes a value from json for the specified path.
func Escape
func Escape(comp string) stringEscape 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
// Prichardfunc ForEachLine
func ForEachLine(json string, iterator func(line Result) bool)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 JSONBytes
func JSONBytes(obj any) []byteJSONBytes ...
func JSONDebugData
func JSONDebugData(message any) []byteJSONDebugData func
func JSONDebugDataString
func JSONDebugDataString(message any) stringJSONDebugDataString func
func JSONString
func JSONString(obj any) stringJSON ...
func JSONUnEscape
func JSONUnEscape(obj any) stringPrettyJSON ...
func JSONUnEscapeBytes
func JSONUnEscapeBytes(obj any) []bytePrettyJSONBytes ...
func ModifierExists
func ModifierExists(name string, fn func(json, arg string) string) boolModifierExists returns true when the specified modifier exists.
func Pretty
func Pretty(json []byte) []bytePretty converts the input json into a more human readable format where each element is on it's own line with clear indentation.
func PrettyEscapeJSONBytes
func PrettyEscapeJSONBytes(obj any) []bytePrettyEscapeJSONBytes ...
func PrettyJSON
func PrettyJSON(obj any) stringPrettyJSON ...
func PrettyJSONBytes
func PrettyJSONBytes(obj any) []bytePrettyJSONBytes ...
func PrettyOptions
func PrettyOptions(json []byte, opts *OptionsPretty) []bytePrettyOptions is like Pretty but with customized options.
func PrettyUnEscapeJSON
func PrettyUnEscapeJSON(obj any) stringPrettyUnEscapeJSON ...
func ProtoBinaryBytes
func ProtoBinaryBytes(m proto.Message) []byteJSONBytes ...
func ProtoBinaryString
func ProtoBinaryString(m proto.Message) stringBinaryString ...
func ProtoJSONBytes
func ProtoJSONBytes(m proto.Message) []byteJSONBytes ...
func ProtoJSONString
func ProtoJSONString(m proto.Message) stringJSON ...
func ReadFile
func ReadFile(filePath string, v any) errorReadFile Read JSON file data
func Set
func Set(json, path string, value any) (string, error)Set sets a json value for the specified path. A path is in dot syntax, such as "name.last" or "age". 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. An error is returned if the path is not valid.
A path is a series of keys separated by a dot.
{
"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.1" >> "Alex"func SetBytes
func SetBytes(json []byte, path string, value any) ([]byte, error)SetBytes sets a json value for the specified path. If working with bytes, this method preferred over Set(string(data), path, value)
func SetBytesOptions
func SetBytesOptions(json []byte, path string, value any, opts *OptionsSet) ([]byte, error)SetBytesOptions sets a json value for the specified path with options. If working with bytes, this method preferred over SetOptions(string(data), path, value)
func SetOptions
func SetOptions(json, path string, value any, opts *OptionsSet) (string, error)SetOptions sets a json value for the specified path with options. A path is in dot syntax, such as "name.last" or "age". 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. An error is returned if the path is not valid.
func SetRaw
func SetRaw(json, path, value string) (string, error)SetRaw sets a raw json value for the specified path. This function works the same as Set except that the value is set as a raw block of json. This allows for setting premarshalled json objects.
func SetRawBytes
func SetRawBytes(json []byte, path string, value []byte) ([]byte, error)SetRawBytes sets a raw json value for the specified path. If working with bytes, this method preferred over SetRaw(string(data), path, value)
func SetRawBytesOptions
func SetRawBytesOptions(json []byte, path string, value []byte, opts *OptionsSet) ([]byte, error)SetRawBytesOptions sets a raw json value for the specified path with options. If working with bytes, this method preferred over SetRawOptions(string(data), path, value, opts)
func SetRawOptions
func SetRawOptions(json, path, value string, opts *OptionsSet) (string, error)SetRawOptions sets a raw json value for the specified path with options. This furnction works the same as SetOptions except that the value is set as a raw block of json. This allows for setting premarshalled json objects.
func Spec
func Spec(src []byte) []byteSpec 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
func SpecInPlace(src []byte) []byteSpecInPlace 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 StripComments
func StripComments(src string) stringStripComments strip comments for a JSON string
func Ugly
func Ugly(json []byte) []byteUgly removes insignificant space characters from the input json byte slice and returns the compacted result.
func UglyInPlace
func UglyInPlace(json []byte) []byteUglyInPlace 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 UnmarshalBinary
func UnmarshalBinary(data []byte, m proto.Message) errorUnmarshalBinary for proto
func UnmarshalJSON
func UnmarshalJSON(data []byte, m proto.Message) errorUnmarshalJSON for proto
func Valid
func Valid(json string) boolValid 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
func ValidBytes(json []byte) boolValidBytes 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))
func WriteFile
func WriteFile(filePath string, data any) errorWriteFile write data to JSON file
func WritePretty
func WritePretty(filePath string, data any) errorWritePretty write pretty data to JSON file
type OptionsPretty
OptionsPretty is Pretty options
type OptionsPretty 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
}type OptionsSet
OptionsSet represents additional options for the Set and Delete functions.
type OptionsSet struct {
// Optimistic is a hint that the value likely exists which
// allows for the sjson to perform a fast-track search and replace.
Optimistic bool
// ReplaceInPlace is a hint to replace the input json rather than
// allocate a new json byte slice. When this field is specified
// the input json will not longer be valid and it should not be used
// In the case when the destination slice doesn't have enough free
// bytes to replace the data in place, a new bytes slice will be
// created under the hood.
// The Optimistic flag must be set to true and the input must be a
// byte slice in order to use this field.
ReplaceInPlace bool
}type Result
Result represents a json value that is returned from Get().
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
}func Get
func Get(json, path string) ResultGet 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
func GetBytes(json []byte, path string) ResultGetBytes searches json for the specified path. If working with bytes, this method preferred over Get(string(data), path)
func GetMany
func GetMany(json string, path ...string) []ResultGetMany 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
func GetManyBytes(json []byte, path ...string) []ResultGetManyBytes 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
func Parse(json string) ResultParse 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
func ParseBytes(json []byte) ResultParseBytes parses the json and returns a result. If working with bytes, this method preferred over Parse(string(data))
func (Result) Array
func (t Result) Array() []ResultArray 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) Bool
func (t Result) Bool() boolBool returns an boolean representation.
func (Result) Exists
func (t Result) Exists() boolExists returns true if value exists.
if gjson.Get(json, "name.last").Exists(){
println("value exists")
}func (Result) Float
func (t Result) Float() float64Float returns an float64 representation.
func (Result) ForEach
func (t Result) ForEach(iterator func(key, value Result) bool)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
func (t Result) Get(path string) ResultGet searches result for the specified path. The result should be a JSON array or object.
func (Result) Int
func (t Result) Int() int64Int returns an integer representation.
func (Result) IsArray
func (t Result) IsArray() boolIsArray returns true if the result value is a JSON array.
func (Result) IsBool
func (t Result) IsBool() boolIsBool returns true if the result value is a JSON boolean.
func (Result) IsObject
func (t Result) IsObject() boolIsObject returns true if the result value is a JSON object.
func (Result) Less
func (t Result) Less(token Result, caseSensitive bool) boolLess return true if a token is less than another token. The caseSensitive paramater is used when the tokens are Strings. The order when comparing two different type is:
Null < False < Number < String < True < JSONfunc (Result) Map
func (t Result) Map() map[string]ResultMap 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
func (t Result) Path(json string) stringPath 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
func (t Result) Paths(json string) []stringPaths 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.
func (Result) String
func (t Result) String() stringString returns a string representation of the value.
func (Result) Time
func (t Result) Time() time.TimeTime returns a time.Time representation.
func (Result) Uint
func (t Result) Uint() uint64Uint returns an unsigned integer representation.
func (Result) Value
func (t Result) Value() anyValue returns one of these types:
bool, for JSON booleans
float64, for JSON numbers
Number, for JSON numbers
string, for JSON string literals
nil, for JSON null
map[string]any, for JSON objects
[]any, for JSON arraystype Style
Style is the color 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
}TerminalStyle is for terminals
var TerminalStyle *Styletype Type
Type is Result type
type Type intconst (
// Null is a null json value
Null Type = iota
// False is a json false boolean
False
// Number is json number
Number
// String is a json string
String
// True is a json true boolean
True
// JSON is a raw block of JSON
JSON
)func (Type) String
func (t Type) String() stringString returns a string representation of the type.
Generated by gomarkdoc