jsonata

package
v0.0.0-...-e2c2e32 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2025 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrorCodeD1001 = "D1001" // Example data error code
)

JSONata Error Codes ==================

Error codes follow the JavaScript implementation's taxonomy for consistency across JSONata implementations. Each code category represents a different class of error:

- D1xxx: Data errors (type mismatches, invalid values) - S0xxx: Syntax errors (parsing failures) - T1xxx, T2xxx: Type errors (function signature mismatches) - U0xxx: User errors (undefined functions, variable references)

This ensures that error handling code can work across different JSONata implementations with consistent error identification.

Variables

View Source
var (
	EntryCallbackSymbol     = "jsonata.__evaluate_entry"
	ExitCallbackSymbol      = "jsonata.__evaluate_exit"
	FramePushCallbackSymbol = "jsonata.__createFrame_push"
)

Symbols for callbacks JS: used Symbol.for('jsonata.__evaluate_entry') etc. directly instead of constants

View Source
var Debug bool

Debug enables debug logging when set to true

View Source
var JSONNull = &JSONataNull{}

Singleton instance of JSONataNull

View Source
var ParseSignature = parseSignature

ParseSignature is the exported version of parseSignature

Functions

func IsUndefined

func IsUndefined(value []byte) bool

See if this is an undefined value

func MakeError

func MakeError(code string, message string) error

Make a structured error

func RegisterGlobalFunction

func RegisterGlobalFunction(name string, implementation JSONataFunc, signature string) error

RegisterGlobalFunction registers a custom function globally for all expressions

func SetDefaultMaxDepth

func SetDefaultMaxDepth(maxDepth int)

SetDefaultMaxDepth sets the global default maximum recursion depth for all new expressions A value of 0 means unlimited depth (default)

func SetDefaultMaxRange

func SetDefaultMaxRange(maxRange int)

SetDefaultMaxRange sets the global default maximum size for range expressions for all new expressions A value of 0 means unlimited range (default)

func SetDefaultMaxTime

func SetDefaultMaxTime(maxMs int)

SetDefaultMaxTime sets the global default maximum execution time for all new expressions A value of 0 means unlimited time (default) Time is specified in milliseconds

func Version

func Version() string

Version returns the current version of the JSONata Go implementation

Types

type ASTNode

type ASTNode struct {
	Type               string
	Value              interface{}
	Position           int
	LHS                *ASTNode
	RHS                *ASTNode
	RHSTerms           []*SortTerm
	RHSPairs           [][2]*ASTNode
	LHSPairs           [][2]*ASTNode
	Expressions        []*ASTNode
	Expression         *ASTNode
	Arguments          []*ASTNode
	Procedure          *ASTNode
	Steps              []*ASTNode
	Focus              string
	Index              string
	Pattern            *ASTNode
	Update             *ASTNode
	Delete             *ASTNode
	Condition          *ASTNode
	Then               *ASTNode
	Else               *ASTNode
	Body               *ASTNode
	Name               string
	ID                 string
	Predicate          []*Stage
	Stages             []*Stage
	Terms              []*SortTerm
	Group              *Group
	KeepArray          bool
	KeepSingletonArray bool
	ConsArray          bool
	Tuple              bool
	NextFunction       string
	Thunk              bool
	Signature          *SignatureValidator
	Ancestor           *AncestorSlot
	SeekingParent      []*AncestorSlot
	Slot               *AncestorSlot
	Error              error
	Errors             []error
	Remaining          []*Token
}

ASTNode represents a node in the abstract syntax tree

func Parse

func Parse(expr string) (*ASTNode, error)

Parse parses a JSONata expression string and returns an AST This is the main exported function that takes an expression string and returns an AST

func ParseWithRecovery

func ParseWithRecovery(expr string) (*ASTNode, error)

ParseWithRecovery parses a JSONata expression string with error recovery enabled Returns an AST that may contain error nodes for invalid syntax

type AncestorSlot

type AncestorSlot struct {
	Label string
	Level int
	Index int
}

AncestorSlot represents an ancestor reference

type ApplyTo

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

ApplyTo represents the context for function application

type DateTimeFormat

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

DateTimeFormat represents analyzed datetime picture

type DateTimeModule

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

DateTimeModule contains date/time formatting functions

type DateTimePart

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

DateTimePart represents a part of datetime format

type Environment

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

Environment represents the JSONata environment (placeholder)

type Expression

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

Expression - Compiled JSONata Expression Ready for Evaluation ==========================================================

An Expression represents a compiled JSONata expression that can be evaluated multiple times against different input data. The expression encapsulates:

Fields: - ast: The parsed Abstract Syntax Tree representing the expression structure - environment: Lexical scope containing function bindings and variables - errors: Any parse errors collected during recovery mode parsing - timestamp: Shared timestamp ensuring $now()/$millis() consistency within evaluation

The Expression maintains immutable state after compilation, allowing safe concurrent evaluation against different input data while preserving the original expression semantics.

func Compile

func Compile(expr string, recoveryMode bool) (compiledExpr *Expression, compileErr error)

Compile - Main Entry Point and Expression Compilation =====================================================

This function parses a JSONata expression string into an executable Expression object. The compilation process involves: 1. Parsing the expression into an Abstract Syntax Tree (AST) 2. Setting up the execution environment with built-in functions 3. Preparing timestamp functions ($now, $millis) for consistent evaluation

Parameters:

  • expr: JSONata expression string (e.g., "$.person.name", "$sum(values)", "books[price > 10]")
  • recover: Enable error recovery mode for parsing invalid syntax. When true, parsing attempts to continue past syntax errors and collects error information for debugging

Returns: - Compiled Expression ready for evaluation against JSON data - Error if expression syntax is invalid

The Expression encapsulates: - Parsed AST representation of the expression - Evaluation environment with function bindings - Timestamp for consistent $now()/$millis() results across evaluation

func (*Expression) AST

func (e *Expression) AST() interface{}

AST returns the parsed AST

func (*Expression) Assign

func (e *Expression) Assign(name string, value interface{})

Assign assigns a value to a variable in the expression's environment

func (*Expression) Errors

func (e *Expression) Errors() []error

Errors returns any parsing errors

func (*Expression) Evaluate

func (e *Expression) Evaluate(inputJSON []byte, bindings map[string]interface{}) (resultJSON []byte, evalErr error)

Evaluate - Execute JSONata Expression Against Input Data ======================================================

This method evaluates the compiled JSONata expression against input JSON data, applying the sequence processing model and context management that define JSONata's behavior.

Key Evaluation Steps:

1. **Error Checking**: Validates that expression compiled successfully 2. **Environment Setup**: Creates execution context with variable bindings 3. **Context Binding**: Establishes root context ($) for path navigation 4. **Timestamp Capture**: Updates temporal functions for consistent time values 5. **Array Wrapping**: Wraps input arrays to preserve JSONata semantics 6. **Expression Evaluation**: Executes the AST against prepared input/context 7. **Result Processing**: Applies sequence flattening rules to output

Parameters: - input: JSON data to evaluate against (any valid JSON value) - bindings: Optional variable bindings for the evaluation context

Returns: - Evaluated result following JSONata's sequence processing rules - Error if evaluation fails or expression had compilation errors

Critical Array Handling: When input is a JSON array, it gets wrapped in a sequence with outerWrapper=true. This preserves the semantic difference between: - Input arrays (preserved structure): [1,2,3] remains [1,2,3] - Result sequences (subject to flattening): path results become flattened

The outerWrapper flag tells the sequence processing engine that this represents an input array rather than a computed sequence, preventing inappropriate flattening.

Evaluate evaluates the expression with JSON input and returns JSON output

func (*Expression) RegisterFunction

func (e *Expression) RegisterFunction(name string, implementation JSONataFunc, signature string) error

RegisterFunction registers a custom function

func (*Expression) SetMaxDepth

func (e *Expression) SetMaxDepth(maxDepth int)

SetMaxDepth sets the maximum recursion depth for the expression A value of 0 means unlimited depth (default)

func (*Expression) SetMaxRange

func (e *Expression) SetMaxRange(maxRange int)

SetMaxRange sets the maximum size for range expressions A value of 0 means unlimited range (default) This prevents denial-of-service attacks using expressions like [1..1000000000]

func (*Expression) SetMaxTime

func (e *Expression) SetMaxTime(maxMs int)

SetMaxTime sets the maximum execution time for the expression A value of 0 means unlimited time (default) This prevents runaway expressions from consuming excessive CPU time

type Focus

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

Focus represents the execution context

type Frame

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

Frame represents an environment frame

type Function

type Function struct {
	JSONataFunction bool
	JSONataLambda   bool
	Implementation  interface{}

	Arity int
	// contains filtered or unexported fields
}

Function represents a JSONata function

type FunctionsModule

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

FunctionsModule contains all the built-in functions

type Global

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

Global represents global state

type Group

type Group struct {
	LHS                 [][2]*ASTNode
	Position            int
	IsObjectConstructor bool // True if this group is from an object constructor expression
}

Group represents a group-by clause

type GroupingSeparator

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

GroupingSeparator represents a grouping separator

type IntegerFormat

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

IntegerFormat represents analyzed integer picture

type JSONataArray

type JSONataArray struct {
	// Array data - equivalent to the JavaScript array's indexed elements
	Data []interface{} `json:"-"`

	// JSONata-specific properties that can be attached to arrays, just like JavaScript
	Sequence      *bool `json:"sequence,omitempty"`      // JavaScript: array.sequence = true
	TupleStream   *bool `json:"tupleStream,omitempty"`   // JavaScript: array.tupleStream = true
	KeepSingleton *bool `json:"keepSingleton,omitempty"` // JavaScript: array.keepSingleton = true
	OuterWrapper  *bool `json:"outerWrapper,omitempty"`  // JavaScript: array.outerWrapper = true
	Cons          *bool `json:"cons,omitempty"`          // JavaScript: array.cons = true
}

JSONataArray represents a property-enhanced array identical to JavaScript In JavaScript: var arr = [1,2,3]; arr.sequence = true; arr.outerWrapper = true; This struct contains a slice and adds the JSONata-specific properties as fields

func (*JSONataArray) Get

func (a *JSONataArray) Get(i int) interface{}

func (*JSONataArray) IsCons

func (a *JSONataArray) IsCons() bool

IsCons checks if cons property is true

func (*JSONataArray) IsKeepSingleton

func (a *JSONataArray) IsKeepSingleton() bool

IsKeepSingleton checks if keepSingleton property is true

func (*JSONataArray) IsOuterWrapper

func (a *JSONataArray) IsOuterWrapper() bool

IsOuterWrapper checks if outerWrapper property is true

func (*JSONataArray) IsSequence

func (a *JSONataArray) IsSequence() bool

IsSequence checks if sequence property is true, like JavaScript: array.sequence === true

func (*JSONataArray) IsTupleStream

func (a *JSONataArray) IsTupleStream() bool

IsTupleStream checks if tupleStream property is true

func (*JSONataArray) Length

func (a *JSONataArray) Length() int

Array-like operations that work exactly like JavaScript

func (*JSONataArray) MarshalJSON

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

MarshalJSON implements json.Marshaler for JSONataArray This ensures that when a JSONataArray is serialized to JSON, it serializes as its Data array rather than as an object with the JSONata metadata fields

func (*JSONataArray) Push

func (a *JSONataArray) Push(item interface{})

func (*JSONataArray) SetCons

func (a *JSONataArray) SetCons(val bool)

SetCons sets the cons property

func (*JSONataArray) SetKeepSingleton

func (a *JSONataArray) SetKeepSingleton(val bool)

SetKeepSingleton sets the keepSingleton property

func (*JSONataArray) SetOuterWrapper

func (a *JSONataArray) SetOuterWrapper(val bool)

SetOuterWrapper sets the outerWrapper property like JavaScript: array.outerWrapper = true

func (*JSONataArray) SetSequence

func (a *JSONataArray) SetSequence(val bool)

SetSequence sets the sequence property like JavaScript: array.sequence = true

func (*JSONataArray) SetTupleStream

func (a *JSONataArray) SetTupleStream(val bool)

SetTupleStream sets the tupleStream property

type JSONataError

type JSONataError struct {
	Code      string      // Standardized JSONata error code
	Value     interface{} // Primary problematic value
	Value2    interface{} // Secondary value (for binary operations)
	Stack     string      // Go stack trace for debugging
	Position  int         // Source position where error occurred
	Token     string      // Token that caused parsing error
	Index     int         // Parameter index for function errors
	Message   string      // Human-readable error description
	Exp       interface{} // Expected value or type
	Type      string      // Actual type that caused error
	Remaining interface{} // Additional error context
}

JSONataError - Structured Error Type with Rich Context =====================================================

JSONataError provides comprehensive error information for debugging and user feedback. It extends Go's standard error interface with JSONata-specific context information that matches the JavaScript implementation's error model.

Fields: - Code: Standardized error code (e.g., "T2001", "D3020") - Value: The problematic value that caused the error - Value2: Secondary value for binary operation errors - Stack: Go stack trace for debugging - Position: Character position in source expression - Token: The token that caused a parsing error - Index: Parameter index for function argument errors - Message: Human-readable error description - Exp: Expected value or type information - Type: Actual type that caused the mismatch - Remaining: Additional context for complex errors

This structure enables detailed error reporting that helps users understand both what went wrong and where in their expression the error occurred.

func (*JSONataError) Error

func (e *JSONataError) Error() string

Error - Standard Go Error Interface Implementation ===============================================

Provides string representation of JSONataError for compatibility with Go's standard error handling. Formats the error code and primary value in a consistent, readable format.

type JSONataFunc

type JSONataFunc func(args []interface{}) (interface{}, error)

JSONataFunc is the unified function signature for all JSONata functions This enables consistent function handling and user-defined functions

type JSONataNull

type JSONataNull struct{}

JSONataNull represents an explicit null value (as opposed to undefined) This allows us to distinguish between JavaScript's null and undefined

func (*JSONataNull) MarshalJSON

func (n *JSONataNull) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler to serialize as JSON null

func (*JSONataNull) String

func (n *JSONataNull) String() string

String representation for debugging

type Lambda

type Lambda struct {
	JSONataLambda bool

	Arity          int
	Implementation func(...interface{}) (interface{}, error)
	// contains filtered or unexported fields
}

Lambda represents a JSONata lambda function

type MatchResult

type MatchResult struct {
	Match  string
	Start  int
	End    int
	Groups []string
	Next   func() *MatchResult
}

MatchResult represents the result of a regex match

type Matcher

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

Matcher represents regex matcher with parse function

type MatcherPart

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

MatcherPart represents a part of a matcher

type Sequence

type Sequence = JSONataArray

Sequence - alias for compatibility

type SignatureParam

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

SignatureParam represents a parameter in a function signature

type SignatureValidator

type SignatureValidator struct {
	Definition string
	Validate   func([]interface{}, interface{}) ([]interface{}, error)
}

SignatureValidator represents a parsed signature with validation

type SortTerm

type SortTerm struct {
	Descending bool
	Expression *ASTNode
}

SortTerm represents a sort term

type Stage

type Stage struct {
	Type     string
	Expr     *ASTNode
	Value    string
	Position int
}

Stage represents a predicate or index stage

type Symbol

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

Symbol represents a parser symbol

type Token

type Token struct {
	Type     string
	Value    interface{}
	Position int
}

Token represents a lexical token

type WidthDef

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

WidthDef represents width definition

type YearMonth

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

YearMonth helper struct

Jump to

Keyboard shortcuts

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