jsonnav

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2025 License: MIT Imports: 4 Imported by: 0

README

JSONNAV

jsonnav is a Go package for accessing, navigating and manipulating values from an untyped json document.

Features

  • Retrieving values from deeply nested json documents safely.
  • Built-in type check functions and conversions.
  • Iterate over arrays and objects.
  • Supports GJSON syntax for navigating the json document.
  • Set or delete values in place.

It supports retrieving deeply nested values safely, as well as iterating over arrays and objects.

Installing

go get github.com/jorgebay/jsonnav

Build

Usage

v, err := jsonnav.Unmarshal(`{"name":{"first":"Jimi","last":"Hendrix"},"age":27}`)
v.Get("name").Get("first").String() // "Jimi"
v.Get("name.last").String() // "Hendrix"
v.Get("age").Float() // 27.0
v.Get("path").Get("does").Get("not").Get("exist").Exists() // false
v.Get("path.does.not.exist").Exists() // false

It uses GJSON syntax for navigating the json document.

Accessing values that may not exist

It's safe to access values that may not exist. The library will return a scalar Value representation with nil underlying value.

v, err := jsonnav.Unmarshal(`{
    "name": {"first":"Jimi", "last":"Hendrix"},
    "instruments": [{"name": "guitar"}]
}`)
v.Get("birth").Get("date").Exists() // false
v.Get("instruments").Array().At(0).Get("name").String() // "guitar"
v.Get("instruments").Array().At(1).Get("name").String() // ""
Setting and deleting values

You can set or delete values in place using Set() and Delete() methods.

v, err := jsonnav.Unmarshal(`{"name":{"first":"Jimi","last":"Hendrix"},"age":27}`)
v.Get("name").Set("middle", "Marshall")
v.Set("birth.date", "1942-11-27")
v.Delete("age")

v.Get("birth").Get("date").String()  // "1942-11-27"
v.Get("name").Get("middle").String() // "Marshall"
Type checks and conversions

The library provides built-in functions for type checks and conversions that are safely free of errors and panics.

Type check functions
v, err := jsonnav.Unmarshal(`{"name":"Jimi","age":27}`)
v.Get("name").IsString()     // true
v.Get("age").IsFloat()       // true
v.Get("age").IsBool()        // false
v.Get("age").IsObject()      // false
v.Get("age").IsArray()       // false
v.Get("not_found").IsNull()  // true
v.Get("not_found").IsEmpty() // true
Typed getters
v, err := jsonnav.Unmarshal(`{
    "name": "Jimi",
    "age": 27,
    "instruments": ["guitar"],
    "hall_of_fame": true
}`)
v.Get("name").String()       // "Jimi"
v.Get("age").Float()         // 27.0
v.Get("hall_of_fame").Bool() // true
v.Get("instruments").Array() // a slice of 1 Value with underlying value "guitar"

When the value doesn't match the expected type or it does not exist, it will default to a zero value of the expected type and do conversions for scalars.

  • String() returns the string representation of float and bool values, otherwise an empty string.
  • Float() returns the float representation of string values, for other types it returns 0.0.
  • Bool() returns the bool representation of string values, for other types it returns false.
  • Array() returns an empty slice for non-array values.
Parsing

The library uses Golang built-in json marshallers. In case you want to use a custom marshaller, you can use jsonnav.From[T]() or jsonnav.FromAny() by providing the actual value.

v, err := jsonnav.From(map[string]any{"name": "John", "age": 30})
v.Get("name").String() // "John"

License

jsonnav is distributed under MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Marshal

func Marshal(value Value) (string, error)

Marshal returns the json string for the provided Value.

func MarshalMap

func MarshalMap(m *Map) (string, error)

MarshalMap returns the json string for the provided map.

Types

type JSONValue

type JSONValue interface {
	float64 | string | bool | map[string]any | []any
}

JSONValue is the type constraint for a json value.

type Map

type Map struct {
	// contains filtered or unexported fields
}

Map represents a JSON object.

func FromJSONMap

func FromJSONMap(m map[string]any) *Map

FromJSONMap creates a new Map from a map[string]any. It expects that the internal map is already a valid json map (composed only by arrays, maps and scalars).

Note that the provided map is not copied, so any modification in the original map will reflect in the Map.

func MustUnmarshalMap

func MustUnmarshalMap(v string) *Map

MustUnmarshalMap is a non-fallible version of UnmarshalMap() used for static variables and tests.

func UnmarshalMap

func UnmarshalMap(v string) (*Map, error)

UnmarshalMap parses the json and returns the map.

func (*Map) Array

func (m *Map) Array() Slice

Array returns an empty slice for maps.

func (*Map) Bool

func (m *Map) Bool() bool

IsInt returns false for maps.

func (*Map) Delete

func (m *Map) Delete(path string) Value

Delete removes the value at the specified path.

func (*Map) Exists

func (m *Map) Exists() bool

Exists returns true if the value is defined.

func (*Map) Float

func (m *Map) Float() float64

Float returns 0 for maps.

func (*Map) Get

func (m *Map) Get(path string) Value

Get searches json for the specified path.

func (*Map) Int

func (m *Map) Int() int64

Int returns 0 for maps.

func (*Map) IsArray

func (*Map) IsArray() bool

IsArray returns false for maps.

func (*Map) IsBool

func (*Map) IsBool() bool

IsBool returns false for maps.

func (*Map) IsEmpty

func (m *Map) IsEmpty() bool

IsEmpty returns true if the map does not have any items.

func (*Map) IsFloat

func (*Map) IsFloat() bool

IsFloat returns false for maps.

func (*Map) IsNull

func (*Map) IsNull() bool

IsNull returns false for maps.

func (*Map) IsObject

func (*Map) IsObject() bool

IsObject returns true for maps.

func (*Map) IsString

func (*Map) IsString() bool

IsString returns false for maps.

func (*Map) Map

func (m *Map) Map() map[string]Value

Map returns the underlying map.

func (*Map) Set

func (m *Map) Set(path string, rawValue any) Value

Set updates the value at the specified path.

func (*Map) String

func (m *Map) String() string

String returns an empty string for maps.

func (*Map) Value

func (m *Map) Value() any

Value returns the underlying map.

type Slice

type Slice []Value

Slice represents an array of values.

func (Slice) Array

func (s Slice) Array() Slice

Array returns the same instance.

func (Slice) At

func (s Slice) At(index int) Value

At returns the value at the specified index. If the index is out of range, it returns an scalar with an internal nil value.

func (Slice) Bool

func (s Slice) Bool() bool

Bool returns false for slices.

func (Slice) Delete

func (s Slice) Delete(path string) Value

Delete removes the value at the specified path.

func (Slice) Exists

func (s Slice) Exists() bool

Exists returns true for slices.

func (Slice) Float

func (s Slice) Float() float64

Float returns 0 for slices.

func (Slice) Get

func (s Slice) Get(path string) Value

Get searches for the specified path within the slice.

func (Slice) Int

func (s Slice) Int() int64

Int returns 0 for slices.

func (Slice) IsArray

func (s Slice) IsArray() bool

IsArray returns true for slices.

func (Slice) IsBool

func (s Slice) IsBool() bool

IsBool returns false for slices.

func (Slice) IsEmpty

func (s Slice) IsEmpty() bool

IsEmpty returns true if the slice does not have any items.

func (Slice) IsFloat

func (s Slice) IsFloat() bool

IsFloat returns false for slices.

func (Slice) IsNull

func (s Slice) IsNull() bool

IsNull returns false for slices.

func (Slice) IsObject

func (s Slice) IsObject() bool

IsObject returns false for slices.

func (Slice) IsString

func (s Slice) IsString() bool

IsString returns false for slices.

func (Slice) Map

func (s Slice) Map() map[string]Value

Map returns an empty map for slices.

func (Slice) Set

func (s Slice) Set(path string, rawValue any) Value

Set sets the value at the specified path.

func (Slice) String

func (s Slice) String() string

String returns an empty string for slices.

func (Slice) Value

func (s Slice) Value() any

Value returns the inner values as a slice.

type Value

type Value interface {
	// Exists returns true if value exists.
	Exists() bool

	// IsEmpty returns true if the value is
	//   - a null JSON value
	//   - an object containing no items
	//   - an array of zero length
	//   - an empty string
	IsEmpty() bool

	// IsNull returns true when the value is representation of the JSON null value.
	IsNull() bool

	// IsArray returns true if the value is a JSON array.
	IsArray() bool

	// IsObject returns true if the value is a JSON object/map.
	IsObject() bool

	// IsString returns true if the value is a string scalar.
	IsString() bool

	// IsFloat returns true if the value is a float/number scalar.
	IsFloat() bool

	// IsBool returns true if the value is a bool scalar.
	IsBool() bool

	// Bool returns a boolean representation.
	// When the value is not a boolean scalar, it returns false.
	Bool() bool

	// Float returns a float64 representation.
	// When the value is not a number scalar, it returns 0.
	Float() float64

	// Int returns an integer representation.
	// When the value is not a number scalar, it returns 0.
	Int() int64

	// String returns a string representation of the value.
	// If the internal value is a bool or float64 scalar, it will be converted to string.
	// If the internal value is a JSON object or array, it will return empty string.
	String() string

	// 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
	Value() any

	// Get searches for the specified path.
	Get(path string) Value

	// Set sets the value in the provided path and returns the modified instance.
	// If the path does not exist, it will be created.
	Set(path string, rawValue any) Value

	// Delete deletes the value in the provided path and returns the modified instance.
	Delete(path string) Value

	// 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.
	Array() Slice

	// 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.
	Map() map[string]Value
}

Value represents the result of a path search expression over a json element. For example: `value.Get("a.b")` will access the value in the object at the path "a.b".

Get() and `Set()` methods partially supports GJSON syntax: https://github.com/tidwall/gjson/blob/master/SYNTAX.md

Not supported expressions: - Nested conditions like "friends.#(nets.#(=="fb"))#". - Tilde comparison.

func From

func From[T JSONValue](value T) Value

From creates a new Value from a JSONValue.

It panics if the value is not float64, string, bool, map or array. In the case of maps and slices it expects the child values to be composed only by valid json values (float64, string, bool, map and slice). Note that the provided value is not copied, so any modification in the original map/slice will reflect in the Value.

func FromAny

func FromAny(value any) Value

FromAny creates a new Value from an any value.

In the case of maps and slices it expects the child values to be composed only by valid json values (float64, string, bool, map and slice). Note that the provided value is not copied, so any modification in the original map/slice will reflect in the Value.

func MustUnmarshalScalar

func MustUnmarshalScalar(v string) Value

MustUnmarshalScalar parses the json and returns the scalar value.

func Unmarshal

func Unmarshal(jsonString string) (Value, error)

Unmarshal parses the json and returns the Value.

Jump to

Keyboard shortcuts

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