gojson

package module
v0.0.0-...-2ca02c9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2023 License: MIT Imports: 10 Imported by: 0

README

gojson

Gojson is a lightweight and fast JSON parser for Go. It is inspired by gjson, but adds a new Set method to make it easier to modify existing JSON documents.

Installation

To install gojson, use go get:

go get github.com/leowilbur/gojson

Usage

Gojson provides a simple API for parsing and manipulating JSON documents.

Parsing

To parse a JSON document, use the Parse function:

data := `{"name": "John Doe", "age": 42}`

json, err := gojson.Parse(data)
if err != nil {
    // handle error
}
Accessing Values

Once you have parsed a JSON document, you can access its values using the Get method:

name := json.Get("name").String() // "John Doe"
age := json.Get("age").Int() // 42
Modifying Values

Gojson also provides a Set method for modifying existing values in a JSON document:

gojson.Set("name", "Jane Doe")
gojson.Set("age", 43)
Serializing

To serialize a JSON document, use the String method:

data := json.String() // {"name": "Jane Doe", "age": 43}

License

Gojson is released under the MIT license. See LICENSE for details.

Documentation

Overview

Package gjson provides searching for json strings.

Index

Constants

This section is empty.

Variables

View Source
var DisableModifiers = false

DisableModifiers will disable the modifier syntax

Functions

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) []byte

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

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

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

ModifierExists returns true when the specified modifier exists.

func Set

func Set(json, path string, value interface{}) (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 interface{}) ([]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 interface{},
	opts *Options) ([]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 interface{},
	opts *Options) (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 *Options) ([]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 *Options) (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 Valid

func Valid(json string) bool

Valid returns true if the input is valid json.

if !Valid(json) {
	return errors.New("invalid json")
}
value := Get(json, "name.last")

func ValidBytes

func ValidBytes(json []byte) bool

ValidBytes returns true if the input is valid json.

if !Valid(json) {
	return errors.New("invalid json")
}
value := Get(json, "name.last")

If working with bytes, this method preferred over ValidBytes(string(data))

Types

type Options

type Options 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
}

Options represents additional options for the Set and Delete functions.

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

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

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

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

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

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

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

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

func (t Result) Bool() bool

Bool returns an boolean representation.

func (Result) Exists

func (t Result) Exists() bool

Exists returns true if value exists.

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

func (Result) Float

func (t Result) Float() float64

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

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

func (Result) Int

func (t Result) Int() int64

Int returns an integer representation.

func (Result) IsArray

func (t Result) IsArray() bool

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

func (Result) IsBool

func (t Result) IsBool() bool

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

func (Result) IsObject

func (t Result) IsObject() bool

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

func (Result) Less

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

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

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:

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) []string

Paths returns the original GJSON paths for a Result where the Result came from a simple query path that returns an array, like:

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

func (t Result) Set(path string, value interface{})

func (Result) String

func (t Result) String() string

String returns a string representation of the value.

func (Result) Time

func (t Result) Time() time.Time

Time returns a time.Time representation.

func (Result) Uint

func (t Result) Uint() uint64

Uint returns an unsigned integer representation.

func (Result) Value

func (t Result) Value() interface{}

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]interface{}, for JSON objects
[]interface{}, for JSON arrays

type Type

type Type int

Type is Result type

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

func (t Type) String() string

String returns a string representation of the type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL