Documentation
¶
Overview ¶
Package djson provides mutable, ordered JSON objects and arrays.
DynamicJSON is not safe for concurrent use involving mutation. After Freeze returns, the complete tree is read-only and safe for concurrent readers. Freezing is irreversible, while Clone returns a mutable copy.
Mutation normalizes signed integers to int64, unsigned integers to uint64, float64 values to float64, and float32 values to json.Number. Parsed numbers remain json.Number to preserve their spelling. time.Duration values are stored as strings, and time.Time values as UTC RFC3339 strings.
Parse accepts only an object or array at the top level, unlike encoding/json, which also accepts scalar JSON values. Parse reports excessive nesting as an error; recursive operations such as serialization, Clone, Freeze, Visit, and IsEqual panic when MaxNestingDepth is exceeded.
Index ¶
- Constants
- func ToBool(v any) (bool, bool)
- func ToFloat(v any, defaultValue float64) float64
- func ToInt(v any, defaultValue int) int
- func ToString(v any, defaultValue string) string
- type DynamicJSON
- func FromFile(filepath string) (r *DynamicJSON, err error)
- func FromResponse(resp *http.Response, err0 error) (*DynamicJSON, error)
- func FromResponse200(resp *http.Response, err0 error) (*DynamicJSON, error)
- func NewArray() *DynamicJSON
- func NewMap() *DynamicJSON
- func Parse(data []byte) (*DynamicJSON, error)
- func (d *DynamicJSON) Append(v any)
- func (d *DynamicJSON) Array(name string) *DynamicJSON
- func (d *DynamicJSON) ArrayI(i int) *DynamicJSON
- func (d *DynamicJSON) Clear()
- func (d *DynamicJSON) Clone() *DynamicJSON
- func (d *DynamicJSON) Delete(path string)
- func (d *DynamicJSON) DeleteKey(key string)
- func (d *DynamicJSON) Each(path string) iter.Seq[*DynamicJSON]
- func (d *DynamicJSON) EachPair(path string) iter.Seq2[string, any]
- func (d *DynamicJSON) Fetch(path string) (any, bool)
- func (d *DynamicJSON) Freeze()
- func (d *DynamicJSON) Get(path string) any
- func (d *DynamicJSON) GetAnySlice(path string) []any
- func (d *DynamicJSON) GetBool(path string, defaultValue bool) bool
- func (d *DynamicJSON) GetBoolsSlice(path string) []bool
- func (d *DynamicJSON) GetDuration(path string, defaultValue time.Duration) time.Duration
- func (d *DynamicJSON) GetFloat(path string, defaultValue float64) float64
- func (d *DynamicJSON) GetFloatsSlice(path string) []float64
- func (d *DynamicJSON) GetI(i int) any
- func (d *DynamicJSON) GetInt(path string, defaultValue int) int
- func (d *DynamicJSON) GetIntsSlice(path string) []int
- func (d *DynamicJSON) GetKey(key string) any
- func (d *DynamicJSON) GetSlice(path string) []*DynamicJSON
- func (d *DynamicJSON) GetStr(path string) string
- func (d *DynamicJSON) GetString(path string, defaultValue string) string
- func (d *DynamicJSON) GetStringsSlice(path string) []string
- func (d *DynamicJSON) GetTime(path string) time.Time
- func (d *DynamicJSON) Has(path string) bool
- func (d *DynamicJSON) HasKey(key string) bool
- func (d *DynamicJSON) IsArray() bool
- func (d *DynamicJSON) IsEqual(o *DynamicJSON) bool
- func (d *DynamicJSON) IsFrozen() bool
- func (d *DynamicJSON) Iterate(cb func(key string, value any) bool)
- func (d *DynamicJSON) JSON() []byte
- func (d *DynamicJSON) JSONLine() []byte
- func (d *DynamicJSON) Keys() []string
- func (d *DynamicJSON) Len() int
- func (d *DynamicJSON) Map(name string) *DynamicJSON
- func (d *DynamicJSON) MapI(i int) *DynamicJSON
- func (d *DynamicJSON) MarshalJSON() ([]byte, error)
- func (d *DynamicJSON) Nested(path string) *DynamicJSON
- func (d *DynamicJSON) NestedI(i int) *DynamicJSON
- func (d *DynamicJSON) NestedKey(key string) *DynamicJSON
- func (d *DynamicJSON) Set(path string, value any)
- func (d *DynamicJSON) SetI(i int, value any)
- func (d *DynamicJSON) SetKey(key string, value any)
- func (d *DynamicJSON) UnmarshalJSON(data []byte) error
- func (d *DynamicJSON) Visit(cb func(path string, value any))
Constants ¶
const MaxNestingDepth = 1000
MaxNestingDepth limits Parse and recursive operations. Parse returns an error at the limit; recursive operations panic. Mutable construction may exceed it, but the next recursive operation will panic.
const MaxResponseBodySize int64 = 16 << 20
MaxResponseBodySize limits decoded bodies read by the response helpers.
Variables ¶
This section is empty.
Functions ¶
func ToBool ¶
ToBool converts booleans, strconv.ParseBool strings, and numeric zero or one. The second result reports success.
func ToFloat ¶
ToFloat converts numbers and numeric strings to float64. It returns defaultValue on failure, NaN, or infinity.
Types ¶
type DynamicJSON ¶
type DynamicJSON struct {
// contains filtered or unexported fields
}
DynamicJSON is a mutable, ordered JSON object or array.
func FromFile ¶
func FromFile(filepath string) (r *DynamicJSON, err error)
FromFile reads and parses a JSON object or array from filepath.
func FromResponse ¶
func FromResponse(resp *http.Response, err0 error) (*DynamicJSON, error)
FromResponse closes resp.Body and parses a limited identity or gzip body. On non-200 status it returns both the parsed document and a status error; an invalid error body joins the status and parse errors.
func FromResponse200 ¶
func FromResponse200(resp *http.Response, err0 error) (*DynamicJSON, error)
FromResponse200 is the strict response helper: non-200 status returns a nil document and an error. It closes resp.Body and accepts limited identity or gzip bodies.
func Parse ¶
func Parse(data []byte) (*DynamicJSON, error)
Parse parses a top-level object or array, preserving key order and number spelling. Scalars and excessive nesting return errors. Parse copies data; tokens may reference that complete copy for the lifetime of the tree.
func (*DynamicJSON) Append ¶
func (d *DynamicJSON) Append(v any)
Append adds an array value. Values appended during iteration are not visited.
func (*DynamicJSON) Array ¶
func (d *DynamicJSON) Array(name string) *DynamicJSON
Array returns the child array named by an object key or array index, replacing another value with a new array when needed.
func (*DynamicJSON) ArrayI ¶
func (d *DynamicJSON) ArrayI(i int) *DynamicJSON
ArrayI returns or creates the array at position i. Arrays grow as needed; object positions must exist. Negative and missing object positions panic.
func (*DynamicJSON) Clear ¶
func (d *DynamicJSON) Clear()
Clear removes every value. Clearing an object during iteration is allowed; entries not yet visited are skipped. Clearing an array during iteration panics because removing its elements would shift active indexes.
func (*DynamicJSON) Clone ¶
func (d *DynamicJSON) Clone() *DynamicJSON
Clone returns a mutable deep copy. Frozen state is not copied, and shared subtrees are duplicated independently.
func (*DynamicJSON) Delete ¶
func (d *DynamicJSON) Delete(path string)
Delete removes the value at path. Deleting object keys during iteration is allowed, and keys deleted before they are visited are skipped. Deleting an existing array element during iteration panics because it would shift active indexes. Missing paths are no-ops.
func (*DynamicJSON) DeleteKey ¶
func (d *DynamicJSON) DeleteKey(key string)
DeleteKey removes an immediate object key without parsing it as a path. Missing keys are no-ops; array and frozen receivers panic.
func (*DynamicJSON) Each ¶
func (d *DynamicJSON) Each(path string) iter.Seq[*DynamicJSON]
Each iterates container and null elements of the array at path. Missing or null is empty; scalars and non-array values panic. Additions are not visited, replacements are visible, and Delete or Clear on the array panics.
func (*DynamicJSON) EachPair ¶
EachPair iterates immediate values at path. Object keys are unchanged; array keys are decimal indexes. Additions are not visited, replacements are visible, and deleted object keys are skipped. Delete and Clear panic on an active array.
func (*DynamicJSON) Fetch ¶
func (d *DynamicJSON) Fetch(path string) (any, bool)
Fetch returns the value at path and whether it exists.
func (*DynamicJSON) Freeze ¶
func (d *DynamicJSON) Freeze()
Freeze irreversibly makes the complete tree read-only. A frozen tree is safe for concurrent readers; mutation attempts panic.
func (*DynamicJSON) Get ¶
func (d *DynamicJSON) Get(path string) any
Get returns the value at path, or nil when missing. Use Fetch to distinguish a missing value from JSON null.
func (*DynamicJSON) GetAnySlice ¶
func (d *DynamicJSON) GetAnySlice(path string) []any
GetAnySlice returns a shallow copy of the array at path without converting its elements. Scalars, DynamicJSON containers, and JSON null values are preserved. A missing path, JSON null at path, or a non-array value returns nil; an empty array returns a non-nil empty slice.
func (*DynamicJSON) GetBool ¶
func (d *DynamicJSON) GetBool(path string, defaultValue bool) bool
GetBool converts the value at path with ToBool or returns defaultValue.
func (*DynamicJSON) GetBoolsSlice ¶
func (d *DynamicJSON) GetBoolsSlice(path string) []bool
GetBoolsSlice converts an array with ToBool. Missing or null returns nil; an empty array is non-nil. Non-array or unconvertible elements, including null, panic.
func (*DynamicJSON) GetDuration ¶
GetDuration parses a duration string or interprets a JSON number as seconds. It returns defaultValue for missing, invalid, or overflowing values.
func (*DynamicJSON) GetFloat ¶
func (d *DynamicJSON) GetFloat(path string, defaultValue float64) float64
GetFloat converts the value at path with ToFloat or returns defaultValue.
func (*DynamicJSON) GetFloatsSlice ¶
func (d *DynamicJSON) GetFloatsSlice(path string) []float64
GetFloatsSlice converts an array with ToFloat. Missing or null returns nil; an empty array is non-nil. Non-array or unconvertible elements, including null, panic.
func (*DynamicJSON) GetI ¶
func (d *DynamicJSON) GetI(i int) any
GetI returns the value at position i, or nil when unavailable. A negative position panics.
func (*DynamicJSON) GetInt ¶
func (d *DynamicJSON) GetInt(path string, defaultValue int) int
GetInt converts the value at path with ToInt or returns defaultValue.
func (*DynamicJSON) GetIntsSlice ¶
func (d *DynamicJSON) GetIntsSlice(path string) []int
GetIntsSlice converts an array with ToInt. Missing or null returns nil; an empty array is non-nil. Non-array or unconvertible elements, including null, panic.
func (*DynamicJSON) GetKey ¶
func (d *DynamicJSON) GetKey(key string) any
GetKey returns an immediate object value without parsing key as a path. It returns nil when unavailable; use HasKey to distinguish JSON null.
func (*DynamicJSON) GetSlice ¶
func (d *DynamicJSON) GetSlice(path string) []*DynamicJSON
GetSlice returns container and null elements from the array at path. Missing or null returns nil; an empty array returns a non-nil empty slice. Scalars and non-array values panic.
func (*DynamicJSON) GetStr ¶
func (d *DynamicJSON) GetStr(path string) string
GetStr returns the string stored at path, without conversion, or "".
func (*DynamicJSON) GetString ¶
func (d *DynamicJSON) GetString(path string, defaultValue string) string
GetString converts the value at path with ToString or returns defaultValue.
func (*DynamicJSON) GetStringsSlice ¶
func (d *DynamicJSON) GetStringsSlice(path string) []string
GetStringsSlice converts an array with ToString. Missing or null returns nil; an empty array is non-nil. Non-array or unconvertible elements, including null, panic. Containers become compact JSON.
func (*DynamicJSON) GetTime ¶
func (d *DynamicJSON) GetTime(path string) time.Time
GetTime parses an RFC3339 string or returns the zero time.
func (*DynamicJSON) Has ¶
func (d *DynamicJSON) Has(path string) bool
Has reports whether path exists. A value containing JSON null still exists.
func (*DynamicJSON) HasKey ¶
func (d *DynamicJSON) HasKey(key string) bool
HasKey reports whether an immediate object key exists without interpreting the key as a path. It returns false for an array or nil receiver.
func (*DynamicJSON) IsArray ¶
func (d *DynamicJSON) IsArray() bool
IsArray reports whether d is an array; nil is not an array.
func (*DynamicJSON) IsEqual ¶
func (d *DynamicJSON) IsEqual(o *DynamicJSON) bool
IsEqual reports structural equality. Numerically equal Go and JSON number types compare equal despite representation differences.
func (*DynamicJSON) IsFrozen ¶
func (d *DynamicJSON) IsFrozen() bool
IsFrozen reports whether modifications to this value are prohibited. It returns false for a nil receiver.
func (*DynamicJSON) Iterate ¶
func (d *DynamicJSON) Iterate(cb func(key string, value any) bool)
Iterate visits immediate values in object insertion or array order until cb returns false. Array keys are decimal indexes. Additions are not visited; replacements are visible and deleted object keys are skipped. Delete and Clear panic on an array being iterated.
func (*DynamicJSON) JSON ¶
func (d *DynamicJSON) JSON() []byte
JSON returns an indented JSON representation. A nil receiver is serialized as null. It panics if the value contains a cycle or exceeds MaxNestingDepth; call MarshalJSON directly when these failures must be returned as errors.
func (*DynamicJSON) JSONLine ¶
func (d *DynamicJSON) JSONLine() []byte
JSONLine returns a compact JSON representation. A nil receiver is serialized as null. It panics if the value contains a cycle or exceeds MaxNestingDepth; call MarshalJSON directly when these failures must be returned as errors.
func (*DynamicJSON) Keys ¶
func (d *DynamicJSON) Keys() []string
Keys returns object keys in insertion order or canonical array indexes.
func (*DynamicJSON) Len ¶
func (d *DynamicJSON) Len() int
Len returns the number of object entries or array elements; nil has length 0.
func (*DynamicJSON) Map ¶
func (d *DynamicJSON) Map(name string) *DynamicJSON
Map returns the child object named by an object key or array index, replacing another value with a new object when needed.
func (*DynamicJSON) MapI ¶
func (d *DynamicJSON) MapI(i int) *DynamicJSON
MapI returns or creates the object at position i. Arrays grow as needed; object positions must exist. Negative and missing object positions panic.
func (*DynamicJSON) MarshalJSON ¶
func (d *DynamicJSON) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler. It preserves object key order and the original representation of json.Number values. Cycles and values exceeding MaxNestingDepth are returned as errors.
func (*DynamicJSON) Nested ¶
func (d *DynamicJSON) Nested(path string) *DynamicJSON
Nested returns the object or array at path, or nil for a missing or scalar value.
func (*DynamicJSON) NestedI ¶
func (d *DynamicJSON) NestedI(i int) *DynamicJSON
NestedI returns the container at position i, or nil when unavailable. A negative position panics.
func (*DynamicJSON) NestedKey ¶
func (d *DynamicJSON) NestedKey(key string) *DynamicJSON
NestedKey returns the container at an immediate object key without parsing the key as a path, or nil when unavailable.
func (*DynamicJSON) Set ¶
func (d *DynamicJSON) Set(path string, value any)
Set writes value at a slash-separated path, creating missing containers. During automatic creation, a missing container becomes an array only when the next path segment is a supported canonical decimal index such as "0" or "12". Segments with leading zeros, such as "007", are object keys. A canonical index longer than nine digits panics before modifying the tree. The type of an existing container always takes precedence over this rule.
func (*DynamicJSON) SetI ¶
func (d *DynamicJSON) SetI(i int, value any)
SetI sets position i. Arrays grow with null-filled gaps; objects preserve the existing key. Invalid positions and nil or frozen receivers panic.
func (*DynamicJSON) SetKey ¶
func (d *DynamicJSON) SetKey(key string, value any)
SetKey sets an immediate object key without interpreting the key as a path. It panics when the receiver is nil, an array, or frozen.
func (*DynamicJSON) UnmarshalJSON ¶
func (d *DynamicJSON) UnmarshalJSON(data []byte) error
UnmarshalJSON atomically replaces d with an object or array and may change its kind. JSON null is a no-op; other scalars are unsupported. Frozen or actively iterated receivers return an error.
func (*DynamicJSON) Visit ¶
func (d *DynamicJSON) Visit(cb func(path string, value any))
Visit recursively visits values using Get-compatible paths. Additions are not visited; replacements are visible and deleted object keys are skipped. Delete and Clear panic on an active array. Cycles and excessive depth panic.