jsonjs

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package jsonjs normalizes serialized JSON using JavaScript value semantics. It is shared by native AI, agent and telemetry code and uses only Go.

Index

Constants

View Source
const Null nullValue = 0

Null represents explicit null at optional Go fields whose nil zero value means absent. Nested JSON null values continue to use ordinary nil.

View Source
const Undefined undefinedValue = 0

Variables

This section is empty.

Functions

func ArrayIndex

func ArrayIndex(key string) (uint64, bool)

ArrayIndex recognizes the own-property index keys sorted first by JS.

func DecodeJSON

func DecodeJSON(raw []byte) (any, error)

DecodeJSON reads JSON into nil, bool, float64, string, []any and map[string]any. Numbers use JavaScript's binary64 domain, including overflow. Strings retain lone UTF-16 surrogates as their three-byte WTF-8 encoding; valid pairs use ordinary UTF-8. QuoteString must be used to export those strings losslessly. Maps retain key identity and last duplicate values, but not insertion order.

func DecodeJSONContainers

func DecodeJSONContainers(raw []byte, object func([]Property) any, array func([]any) any) (any, error)

DecodeJSONContainers supplies explicit object/array constructors. Nil constructors retain the ordinary Go map/slice representation. Children are constructed before their parent, after the entire input has been validated.

func DecodeOptional

func DecodeOptional(raw []byte) (any, error)

DecodeOptional retains absence versus null at optional JSON-value fields.

func DecodeValue

func DecodeValue(raw []byte) (any, error)

DecodeValue constructs live ordered objects and reference arrays from JSON.

func IsNull

func IsNull(value any) bool

func IsNullish

func IsNullish(value any) bool

func IsUndefined

func IsUndefined(value any) bool

func MarshalOptional

func MarshalOptional(value any, key ...string) ([]byte, error)

MarshalOptional exports an optional object property. nil/Undefined/functions are omitted; Null exports an explicit JSON null.

func MarshalValue

func MarshalValue(value any) ([]byte, error)

MarshalValue adapts export to Go's json.Marshaler, which requires a JSON value: an undefined root becomes null. StringifyValue preserves root omission instead.

func PropertyReadError

func PropertyReadError(present bool, expression string) error

PropertyReadError retains the pinned runtime's diagnostic for reading a property on null (present) or undefined (absent).

func QuoteString

func QuoteString(value string) []byte

QuoteString exports UTF-8 and decoded WTF-8 strings using JSON.stringify's escaping. Surrogate code units remain escaped; other invalid UTF-8 uses the replacement character, matching the shared serialized-JSON parser.

func StringCodePoints

func StringCodePoints(value string) []rune

StringCodePoints follows JavaScript string iteration. A lone surrogate is one code point, represented by WTF-8 in Go; valid pairs are ordinary UTF-8.

func StringifyJSON

func StringifyJSON(raw []byte) ([]byte, error)

StringifyJSON normalizes serialized JSON using the value semantics of Pi's JSON.parse/JSON.stringify boundary. It preserves insertion order, applies JS index-key and duplicate-key rules, converts numbers to binary64, and retains lone UTF-16 surrogates. Invalid JSON returns the Go decoder's error.

func StringifyProperty

func StringifyProperty(value any, key string) ([]byte, error)

StringifyProperty exports a value at a known property boundary. It lets typed Go host serializers retain the toJSON key and omit undefined hook results.

func StringifyValue

func StringifyValue(value any) ([]byte, error)

StringifyValue follows JSON.stringify for the supported value graph. An undefined/function root, including a hook result, returns no bytes and no error.

func SupportedValue

func SupportedValue(value any) bool

func ValidateJSON

func ValidateJSON(raw []byte) error

ValidateJSON checks strict JSON syntax using the pinned Bun/JavaScriptCore diagnostics. It does not repair input, coerce values, or construct a graph. The explicit parser stack also avoids recursive descent on nested input.

Types

type Array

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

Array retains JavaScript-style identity and length across shared references. Absent indices (holes) differ from present Undefined values in Has/Keys, but both read as Undefined and export as null. Enumerable own data properties outside array indices retain insertion order and do not affect length or JSON. An explicit JSONMethod stored as toJSON can replace the array during export. Custom prototypes and accessors are not represented. Callers must synchronize concurrent reads and writes.

func NewArray

func NewArray(values ...any) *Array

func (*Array) Append

func (a *Array) Append(values ...any) int

func (*Array) Delete

func (a *Array) Delete(index int)

func (*Array) DeleteProperty

func (a *Array) DeleteProperty(name string)

func (*Array) Get

func (a *Array) Get(index int) any

func (*Array) GetProperty

func (a *Array) GetProperty(name string) (any, bool)

GetProperty reads an indexed or named own data property. Inherited properties and the reserved length property are excluded; use Len for length.

func (*Array) Has

func (a *Array) Has(index int) bool

func (*Array) Keys

func (a *Array) Keys() []int

func (*Array) Len

func (a *Array) Len() int

func (*Array) MarshalJSON

func (a *Array) MarshalJSON() ([]byte, error)

func (*Array) Pop

func (a *Array) Pop() any

func (*Array) PropertyKeys

func (a *Array) PropertyKeys() []string

PropertyKeys follows Object.keys order: numeric indices, then named own data properties in insertion order. The non-enumerable length property is excluded.

func (*Array) Set

func (a *Array) Set(index int, value any)

func (*Array) SetLength

func (a *Array) SetLength(length int)

func (*Array) SetProperty

func (a *Array) SetProperty(name string, value any)

SetProperty defines an enumerable own data property. It bypasses prototype setters (including __proto__) and accessors. Use SetLength to change length.

func (*Array) Values

func (a *Array) Values() []any

Values returns a detached, dense outer slice. Holes become Undefined, as in JavaScript array spread; nested objects and arrays retain their identity.

type JSONMethod

type JSONMethod func(receiver any, key string) (any, error)

JSONMethod is an explicit own toJSON hook. Export passes the current object or array as receiver and its containing property key (empty at the root). Recording/cloning never invoke it. Returned errors and panics propagate. Other Go function types and arbitrary serialization methods remain passive.

type Object

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

Object retains own-property insertion order and shared nested identity. Set overwrites in place; Delete followed by Set appends a new property. Entries enumerates numeric index keys first, as Object.entries does in Pi. Callers must synchronize concurrent access. Recording and JSON export never invoke arbitrary user serializers.

func NewObject

func NewObject(properties ...Property) *Object

func (*Object) Delete

func (o *Object) Delete(name string)

func (*Object) Entries

func (o *Object) Entries() []Property

func (*Object) Get

func (o *Object) Get(name string) any

func (*Object) Len

func (o *Object) Len() int

func (*Object) Lookup

func (o *Object) Lookup(name string) (any, bool)

func (*Object) MarshalJSON

func (o *Object) MarshalJSON() ([]byte, error)

func (*Object) Set

func (o *Object) Set(name string, value any)

type ObjectFields

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

ObjectFields builds an object from canonical JSON keys, retaining UTF-16 identity without converting lone surrogates into replacement characters.

func (*ObjectFields) Marshal

func (o *ObjectFields) Marshal() []byte

Marshal orders index keys numerically and retains other insertion positions.

func (*ObjectFields) Set

func (o *ObjectFields) Set(name, value []byte)

Set replaces duplicate values without changing the first insertion position. The name must be a canonical JSON string produced by StringifyJSON.

type ObjectValue

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

ObjectValue is a rebindable reference to an ordered object. Value copies share the object; decoding replaces this reference without changing aliases.

func NewObjectValue

func NewObjectValue(properties ...Property) ObjectValue

NewObjectValue preserves the order of the supplied properties. Its copies share the input object.

func (ObjectValue) Delete

func (a ObjectValue) Delete(name string)

func (ObjectValue) Entries

func (a ObjectValue) Entries() []Property

func (ObjectValue) Get

func (a ObjectValue) Get(name string) any

func (ObjectValue) IsZero

func (a ObjectValue) IsZero() bool

func (ObjectValue) Len

func (a ObjectValue) Len() int

func (ObjectValue) Lookup

func (a ObjectValue) Lookup(name string) (any, bool)

func (ObjectValue) MarshalJSON

func (o ObjectValue) MarshalJSON() ([]byte, error)

func (*ObjectValue) Set

func (a *ObjectValue) Set(name string, value any)

func (*ObjectValue) UnmarshalJSON

func (object *ObjectValue) UnmarshalJSON(raw []byte) error

UnmarshalJSON reads an object using JSON.parse's number domain. Valid numeric overflow becomes infinity, underflow keeps its sign, and all numbers round to binary64. Export remains the responsibility of MarshalJSON; converting overflow to null here would lose the recorded in-memory value. Lone UTF-16 surrogates use WTF-8 within Go strings, including map keys; ObjectValue.MarshalJSON restores their original JSON escapes. Objects and arrays use *Object and *Array, retaining key order and shared nested identity, including array length edits through retained references. Each successful decode replaces the object, including on a reused receiver. A rejected payload leaves the receiver and any aliases untouched.

type Property

type Property struct {
	Name  string
	Value any
}

Property is one JSON object entry. DecodeJSONContainers supplies entries in source order, including duplicates; the builder owns duplicate-key handling.

type RawObject

type RawObject map[string]json.RawMessage

RawObject is a JSON object whose keys retain UTF-16 identity and whose values stay serialized. It is for typed envelopes that must preserve opaque fields, without decoding their numbers or interpreting nested values. Like Go maps, it has no insertion order; export sorts keys for deterministic output.

func (RawObject) MarshalJSON

func (o RawObject) MarshalJSON() ([]byte, error)

func (*RawObject) UnmarshalJSON

func (o *RawObject) UnmarshalJSON(raw []byte) error

Successful decoding replaces the object and owns its raw value bytes. Invalid input leaves the receiver untouched. Repeated keys keep their final value; distinct lone surrogate keys do not collapse into the replacement character.

type RawProperty

type RawProperty struct {
	Name  string
	Value json.RawMessage
}

RawProperty retains a decoded UTF-16 key and its original serialized value.

func DecodeObjectProperties

func DecodeObjectProperties(raw []byte) ([]RawProperty, error)

DecodeObjectProperties reads own properties in source order, including duplicates. Values borrow raw; callers retaining them must not mutate raw. Non-object JSON returns no properties. Invalid JSON returns a decoder error.

type ValueCloner

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

ValueCloner detaches mutable JSON-shaped containers without serialization. One cloner preserves repeated references and cycles across multiple roots. Callers synchronize access to the source graph and to the cloner.

func (*ValueCloner) Clone

func (c *ValueCloner) Clone(value any) any

Jump to

Keyboard shortcuts

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