Skip to content

Import path: gitlab.soludian.com/soludian/fountain/libs/base/fson

fson

go
import "gitlab.soludian.com/soludian/fountain/libs/base/fson"

Index

Variables

DisableModifiers will disable the modifier syntax

go
var DisableModifiers = false

OmitDefaultAPI ...

go
var OmitDefaultAPI = jsoniter.Config{
    SortMapKeys:            true,
    UseNumber:              true,
    CaseSensitive:          true,
    EscapeHTML:             true,
    ValidateJsonRawMessage: true,
}.Froze()

PrettyDefaultOptions is the default options for pretty formats.

go
var PrettyDefaultOptions = &OptionsPretty{Width: 80, Prefix: "", Indent: "  ", SortKeys: false}

func AddModifier

go
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

go
func AppendJSONString(dst []byte, s string) []byte

AppendJSONString is a convenience function that converts the provided string to a valid JSON string and appends it to dst.

func Color

go
func Color(src []byte, style *Style) []byte

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 Delete

go
func Delete(json, path string) (string, error)

Delete deletes a value from json for the specified path.

func DeleteBytes

go
func DeleteBytes(json []byte, path string) ([]byte, error)

DeleteBytes deletes a value from json for the specified path.

func Escape

go
func Escape(comp string) string

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

go
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

go
func JSONBytes(obj any) []byte

JSONBytes ...

func JSONDebugData

go
func JSONDebugData(message any) []byte

JSONDebugData func

func JSONDebugDataString

go
func JSONDebugDataString(message any) string

JSONDebugDataString func

func JSONString

go
func JSONString(obj any) string

JSON ...

func JSONUnEscape

go
func JSONUnEscape(obj any) string

PrettyJSON ...

func JSONUnEscapeBytes

go
func JSONUnEscapeBytes(obj any) []byte

PrettyJSONBytes ...

func ModifierExists

go
func ModifierExists(name string, fn func(json, arg string) string) bool

ModifierExists returns true when the specified modifier exists.

func Pretty

go
func Pretty(json []byte) []byte

Pretty converts the input json into a more human readable format where each element is on it's own line with clear indentation.

func PrettyEscapeJSONBytes

go
func PrettyEscapeJSONBytes(obj any) []byte

PrettyEscapeJSONBytes ...

func PrettyJSON

go
func PrettyJSON(obj any) string

PrettyJSON ...

func PrettyJSONBytes

go
func PrettyJSONBytes(obj any) []byte

PrettyJSONBytes ...

func PrettyOptions

go
func PrettyOptions(json []byte, opts *OptionsPretty) []byte

PrettyOptions is like Pretty but with customized options.

func PrettyUnEscapeJSON

go
func PrettyUnEscapeJSON(obj any) string

PrettyUnEscapeJSON ...

func ProtoBinaryBytes

go
func ProtoBinaryBytes(m proto.Message) []byte

JSONBytes ...

func ProtoBinaryString

go
func ProtoBinaryString(m proto.Message) string

BinaryString ...

func ProtoJSONBytes

go
func ProtoJSONBytes(m proto.Message) []byte

JSONBytes ...

func ProtoJSONString

go
func ProtoJSONString(m proto.Message) string

JSON ...

func ReadFile

go
func ReadFile(filePath string, v any) error

ReadFile Read JSON file data

func Set

go
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

go
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

go
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

go
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

go
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

go
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

go
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

go
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

go
func Spec(src []byte) []byte

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

go
func SpecInPlace(src []byte) []byte

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 StripComments

go
func StripComments(src string) string

StripComments strip comments for a JSON string

func Ugly

go
func Ugly(json []byte) []byte

Ugly removes insignificant space characters from the input json byte slice and returns the compacted result.

func UglyInPlace

go
func UglyInPlace(json []byte) []byte

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 UnmarshalBinary

go
func UnmarshalBinary(data []byte, m proto.Message) error

UnmarshalBinary for proto

func UnmarshalJSON

go
func UnmarshalJSON(data []byte, m proto.Message) error

UnmarshalJSON for proto

func Valid

go
func Valid(json string) bool

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

go
func ValidBytes(json []byte) bool

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))

func WriteFile

go
func WriteFile(filePath string, data any) error

WriteFile write data to JSON file

func WritePretty

go
func WritePretty(filePath string, data any) error

WritePretty write pretty data to JSON file

type OptionsPretty

OptionsPretty is Pretty options

go
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.

go
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().

go
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

go
func Get(json, path string) Result

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

go
func GetBytes(json []byte, path string) Result

GetBytes searches json for the specified path. If working with bytes, this method preferred over Get(string(data), path)

func GetMany

go
func GetMany(json string, path ...string) []Result

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

go
func GetManyBytes(json []byte, path ...string) []Result

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

go
func Parse(json string) Result

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

go
func ParseBytes(json []byte) Result

ParseBytes parses the json and returns a result. If working with bytes, this method preferred over Parse(string(data))

func (Result) Array

go
func (t Result) Array() []Result

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) Bool

go
func (t Result) Bool() bool

Bool returns an boolean representation.

func (Result) Exists

go
func (t Result) Exists() bool

Exists returns true if value exists.

if gjson.Get(json, "name.last").Exists(){
		println("value exists")
 }

func (Result) Float

go
func (t Result) Float() float64

Float returns an float64 representation.

func (Result) ForEach

go
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

go
func (t Result) Get(path string) Result

Get searches result for the specified path. The result should be a JSON array or object.

func (Result) Int

go
func (t Result) Int() int64

Int returns an integer representation.

func (Result) IsArray

go
func (t Result) IsArray() bool

IsArray returns true if the result value is a JSON array.

func (Result) IsBool

go
func (t Result) IsBool() bool

IsBool returns true if the result value is a JSON boolean.

func (Result) IsObject

go
func (t Result) IsObject() bool

IsObject returns true if the result value is a JSON object.

func (Result) Less

go
func (t Result) Less(token Result, caseSensitive bool) bool

Less 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 < JSON

func (Result) Map

go
func (t Result) Map() map[string]Result

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

go
func (t Result) Path(json string) string

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

go
func (t Result) Paths(json string) []string

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.

func (Result) String

go
func (t Result) String() string

String returns a string representation of the value.

func (Result) Time

go
func (t Result) Time() time.Time

Time returns a time.Time representation.

func (Result) Uint

go
func (t Result) Uint() uint64

Uint returns an unsigned integer representation.

func (Result) Value

go
func (t Result) Value() any

Value 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 arrays

type Style

Style is the color style

go
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

go
var TerminalStyle *Style

type Type

Type is Result type

go
type Type int

go
const (
    // 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

go
func (t Type) String() string

String returns a string representation of the type.

Generated by gomarkdoc