API Reference

Core Types

MathJSON.MathJSONFormatType
MathJSONFormat

Singleton type used for dispatch in parse(MathJSONFormat, str) and generate(MathJSONFormat, expr) functions.

source
MathJSON.AbstractMathJSONExprType
AbstractMathJSONExpr

Abstract base type for all MathJSON expression types.

All concrete expression types (NumberExpr, SymbolExpr, StringExpr, FunctionExpr) are subtypes of this abstract type, enabling dispatch-based polymorphism.

source
MathJSON.ExpressionTypeModule
ExpressionType

Module containing the expression type enum. Use scoped access to avoid namespace pollution.

Example

expr_type = ExpressionType.NUMBER
expr_type isa ExpressionType.T  # true
source

Expression Types

MathJSON.NumberExprType
NumberExpr <: AbstractMathJSONExpr

Represents a numeric value in MathJSON format.

Fields

  • value::MathJSONNumber: The numeric value (Int64, Float64, BigFloat, or Rational)
  • raw::Union{Nothing, String}: Original string representation for extended precision
  • metadata::Union{Nothing, Dict{String, Any}}: Optional metadata dictionary

Constructors

NumberExpr(value)                        # Simple numeric value
NumberExpr(value, raw)                   # With raw string for precision
NumberExpr(value, raw, metadata)         # Full constructor
NumberExpr(value; metadata=nothing)      # With keyword metadata

Examples

n1 = NumberExpr(42)
n2 = NumberExpr(3.14, "3.14159265358979323846")
n3 = NumberExpr(1//3)
n4 = NumberExpr(3.14; metadata=Dict("wikidata" => "Q167"))
source
MathJSON.SymbolExprType
SymbolExpr <: AbstractMathJSONExpr

Represents a symbol (variable, constant, or function name) in MathJSON format.

Symbol names are automatically normalized to Unicode NFC form for consistent comparison.

Fields

  • name::String: The symbol name (NFC normalized)
  • metadata::Union{Nothing, Dict{String, Any}}: Optional metadata dictionary

Constructors

SymbolExpr(name)                    # Simple symbol
SymbolExpr(name; metadata=nothing)  # With optional metadata

Valid Identifier Formats

  • Standard: alphanumeric + underscore (e.g., x, my_var, x1)
  • Backtick-wrapped: for non-standard names (e.g., $`x+y`$, $`my var`$)
  • PascalCase: for constants (e.g., Pi, ExponentialE)

Examples

s1 = SymbolExpr("x")
s2 = SymbolExpr("Pi"; metadata=Dict("wikidata" => "Q167"))
s3 = SymbolExpr("`x+y`")  # Non-standard identifier
source
MathJSON.StringExprType
StringExpr <: AbstractMathJSONExpr

Represents a string literal in MathJSON format.

Fields

  • value::String: The string value
  • metadata::Union{Nothing, Dict{String, Any}}: Optional metadata dictionary

Constructors

StringExpr(value)                    # Simple string
StringExpr(value; metadata=nothing)  # With optional metadata

Examples

s1 = StringExpr("hello")
s2 = StringExpr("greeting"; metadata=Dict("comment" => "A greeting"))
source
MathJSON.FunctionExprType
FunctionExpr <: AbstractMathJSONExpr

Represents a function application in MathJSON format.

Fields

  • operator::Symbol: The function/operator name as a Julia Symbol
  • arguments::Vector{AbstractMathJSONExpr}: The function arguments
  • metadata::Union{Nothing, Dict{String, Any}}: Optional metadata dictionary

Constructors

FunctionExpr(operator, arguments)                    # Basic construction
FunctionExpr(operator, arguments; metadata=nothing)  # With optional metadata

Examples

# 1 + 2
f1 = FunctionExpr(:Add, [NumberExpr(1), NumberExpr(2)])

# sin(x)
f2 = FunctionExpr(:Sin, [SymbolExpr("x")])

# (1 + 2) * 3 (nested)
inner = FunctionExpr(:Add, [NumberExpr(1), NumberExpr(2)])
outer = FunctionExpr(:Multiply, [inner, NumberExpr(3)])
source

Parsing

Base.parseMethod
parse(::Type{MathJSONFormat}, str::AbstractString) -> AbstractMathJSONExpr

Parse a MathJSON string into an expression tree.

Arguments

  • str: A valid MathJSON JSON string

Returns

An expression tree (NumberExpr, SymbolExpr, StringExpr, or FunctionExpr)

Throws

  • MathJSONParseError: If the input is not valid MathJSON

Examples

# Parse a number
parse(MathJSONFormat, "42")  # NumberExpr(42)

# Parse a symbol
parse(MathJSONFormat, ""x"")  # SymbolExpr("x")

# Parse a function
parse(MathJSONFormat, "["Add", 1, 2]")  # FunctionExpr(:Add, [NumberExpr(1), NumberExpr(2)])
source

Generation

MathJSON.generateFunction
generate(::Type{MathJSONFormat}, expr::AbstractMathJSONExpr; compact::Bool=true, pretty::Bool=false) -> String

Generate a MathJSON string from an expression tree.

Arguments

  • expr: A MathJSON expression tree
  • compact: If true (default), generate minimal JSON without unnecessary object forms
  • pretty: If true, generate formatted JSON with indentation (default: false)

Returns

A valid MathJSON JSON string

Examples

# Generate a number
generate(MathJSONFormat, NumberExpr(42))  # "42"

# Generate a symbol
generate(MathJSONFormat, SymbolExpr("x"))  # ""x""

# Generate a function
generate(MathJSONFormat, FunctionExpr(:Add, [NumberExpr(1), NumberExpr(2)]))  # "["Add",1,2]"

# Generate with metadata (uses object form)
expr = NumberExpr(3.14; metadata=Dict("wikidata" => "Q167"))
generate(MathJSONFormat, expr)  # "{"num":"3.14","wikidata":"Q167"}"
source

Validation

MathJSON.validateFunction
validate(expr::AbstractMathJSONExpr; strict::Bool=false) -> ValidationResult

Validate a MathJSON expression against the specification.

Arguments

  • expr: The expression to validate
  • strict: If true, also check symbol naming conventions and operator names against the standard library

Returns

A ValidationResult with valid flag and errors vector

Strict Mode Checks

  • Symbol names should follow camelCase (variables) or PascalCase (constants)
  • Operator names should be recognized standard library operators
  • Wildcards (starting with _) are only valid in specific contexts

Examples

# Basic validation
result = validate(NumberExpr(42))
result.valid  # true

# Invalid structure
result = validate(FunctionExpr(:Add, []))  # Missing arguments
result.valid  # true (structurally valid, but semantically questionable)

# Strict mode
result = validate(FunctionExpr(:CustomOp, [NumberExpr(1)]); strict=true)
result.errors  # ["Unknown operator: CustomOp"]
source
MathJSON.ValidationResultType
ValidationResult

Result of validating a MathJSON expression.

Fields

  • valid::Bool: Whether the expression is valid
  • errors::Vector{String}: List of validation error messages (empty if valid)

Examples

result = ValidationResult(true, String[])
result.valid  # true
isempty(result.errors)  # true

result = ValidationResult(false, ["Invalid operator: Foo"])
result.valid  # false
result.errors  # ["Invalid operator: Foo"]
source

Metadata

MathJSON.metadataFunction
metadata(expr::AbstractMathJSONExpr)

Return the metadata dictionary associated with the expression, or nothing if no metadata is present.

Examples

n = NumberExpr(42; metadata=Dict("wikidata" => "Q167"))
metadata(n)  # Dict{String, Any}("wikidata" => "Q167")

s = SymbolExpr("x")
metadata(s)  # nothing
source
MathJSON.with_metadataFunction
with_metadata(expr, key::String, value) -> AbstractMathJSONExpr

Return a new expression with the given key-value pair added to its metadata. If the expression already has metadata, the new key-value is merged in. The original expression is not modified.

Examples

n = NumberExpr(42)
n2 = with_metadata(n, "wikidata", "Q167")
metadata(n2)  # Dict{String, Any}("wikidata" => "Q167")
metadata(n)   # nothing (original unchanged)
source
with_metadata(expr, metadata::Dict{String, Any}) -> AbstractMathJSONExpr

Return a new expression with the given metadata dictionary, replacing any existing metadata. The original expression is not modified.

Examples

n = NumberExpr(42; metadata=Dict("old" => "value"))
n2 = with_metadata(n, Dict{String, Any}("new" => "value"))
metadata(n2)  # Dict{String, Any}("new" => "value")
source

Operators

MathJSON.OperatorCategoryModule
OperatorCategory

Module containing the operator category enum. Use scoped access to avoid namespace pollution.

Example

cat = OperatorCategory.ARITHMETIC
cat isa OperatorCategory.T  # true
source
MathJSON.OPERATORSConstant
OPERATORS::Dict{Symbol, OperatorCategory.T}

Dictionary mapping MathJSON operator symbols to their categories. Loaded from data/operators.json at module initialization.

source
MathJSON.JULIA_FUNCTIONSConstant
JULIA_FUNCTIONS::Dict{Symbol, Function}

Dictionary mapping MathJSON operators to Julia functions. Used for converting MathJSON expressions to executable Julia code and for Symbolics.jl integration. Loaded from data/julia_functions.json at module initialization.

source
MathJSON.get_categoryFunction
get_category(op::Symbol) -> OperatorCategory.T

Return the category for a MathJSON operator, or UNKNOWN if the operator is not recognized.

Examples

get_category(:Add)      # OperatorCategory.ARITHMETIC
get_category(:Sin)      # OperatorCategory.TRIGONOMETRY
get_category(:Custom)   # OperatorCategory.UNKNOWN
source
MathJSON.get_julia_functionFunction
get_julia_function(op::Symbol) -> Union{Function, Nothing}

Return the Julia function corresponding to a MathJSON operator, or nothing if no mapping exists.

Examples

get_julia_function(:Add)     # +
get_julia_function(:Sin)     # sin
get_julia_function(:Custom)  # nothing
source
MathJSON.is_known_operatorFunction
is_known_operator(op::Symbol) -> Bool

Return true if the operator is a known MathJSON standard library operator.

Examples

is_known_operator(:Add)     # true
is_known_operator(:Sin)     # true
is_known_operator(:Custom)  # false
source

Symbolics.jl Integration

MathJSON.to_symbolicsFunction
to_symbolics(expr::AbstractMathJSONExpr)

Convert a MathJSON expression to a Symbolics.jl expression.

This function requires the Symbolics.jl package to be loaded. Load it with using Symbolics before calling this function.

Examples

using Symbolics
expr = parse(MathJSONFormat, "["Add", "x", 1]")
symbolic = to_symbolics(expr)
source
MathJSON.from_symbolicsFunction
from_symbolics(expr)

Convert a Symbolics.jl expression to a MathJSON expression.

This function requires the Symbolics.jl package to be loaded. Load it with using Symbolics before calling this function.

Examples

using Symbolics
@variables x
mathjson = from_symbolics(x + 1)
source

Errors

MathJSON.MathJSONParseErrorType
MathJSONParseError <: Exception

Exception thrown when parsing invalid MathJSON input.

Fields

  • message::String: Description of the parse error
  • position::Union{Nothing, Int}: Optional position in the input where error occurred

Example

throw(MathJSONParseError("Unexpected token", 42))
source
MathJSON.UnsupportedConversionErrorType
UnsupportedConversionError <: Exception

Exception thrown when attempting to convert an unsupported MathJSON expression to Symbolics.jl or vice versa.

Fields

  • message::String: Description of the conversion error

Example

throw(UnsupportedConversionError("Unknown operator: CustomOp"))
source