API Reference
Core Types
MathJSON.MathJSONFormat — Type
MathJSONFormatSingleton type used for dispatch in parse(MathJSONFormat, str) and generate(MathJSONFormat, expr) functions.
MathJSON.AbstractMathJSONExpr — Type
AbstractMathJSONExprAbstract 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.
MathJSON.ExpressionType — Module
ExpressionTypeModule containing the expression type enum. Use scoped access to avoid namespace pollution.
Example
expr_type = ExpressionType.NUMBER
expr_type isa ExpressionType.T # trueExpression Types
MathJSON.NumberExpr — Type
NumberExpr <: AbstractMathJSONExprRepresents 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 precisionmetadata::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 metadataExamples
n1 = NumberExpr(42)
n2 = NumberExpr(3.14, "3.14159265358979323846")
n3 = NumberExpr(1//3)
n4 = NumberExpr(3.14; metadata=Dict("wikidata" => "Q167"))MathJSON.SymbolExpr — Type
SymbolExpr <: AbstractMathJSONExprRepresents 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 metadataValid 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 identifierMathJSON.StringExpr — Type
StringExpr <: AbstractMathJSONExprRepresents a string literal in MathJSON format.
Fields
value::String: The string valuemetadata::Union{Nothing, Dict{String, Any}}: Optional metadata dictionary
Constructors
StringExpr(value) # Simple string
StringExpr(value; metadata=nothing) # With optional metadataExamples
s1 = StringExpr("hello")
s2 = StringExpr("greeting"; metadata=Dict("comment" => "A greeting"))MathJSON.FunctionExpr — Type
FunctionExpr <: AbstractMathJSONExprRepresents a function application in MathJSON format.
Fields
operator::Symbol: The function/operator name as a Julia Symbolarguments::Vector{AbstractMathJSONExpr}: The function argumentsmetadata::Union{Nothing, Dict{String, Any}}: Optional metadata dictionary
Constructors
FunctionExpr(operator, arguments) # Basic construction
FunctionExpr(operator, arguments; metadata=nothing) # With optional metadataExamples
# 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)])Parsing
Base.parse — Method
parse(::Type{MathJSONFormat}, str::AbstractString) -> AbstractMathJSONExprParse 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)])Generation
MathJSON.generate — Function
generate(::Type{MathJSONFormat}, expr::AbstractMathJSONExpr; compact::Bool=true, pretty::Bool=false) -> StringGenerate a MathJSON string from an expression tree.
Arguments
expr: A MathJSON expression treecompact: Iftrue(default), generate minimal JSON without unnecessary object formspretty: Iftrue, 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"}"Validation
MathJSON.validate — Function
validate(expr::AbstractMathJSONExpr; strict::Bool=false) -> ValidationResultValidate a MathJSON expression against the specification.
Arguments
expr: The expression to validatestrict: Iftrue, 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"]MathJSON.ValidationResult — Type
ValidationResultResult of validating a MathJSON expression.
Fields
valid::Bool: Whether the expression is validerrors::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"]Metadata
MathJSON.metadata — Function
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) # nothingMathJSON.with_metadata — Function
with_metadata(expr, key::String, value) -> AbstractMathJSONExprReturn 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)with_metadata(expr, metadata::Dict{String, Any}) -> AbstractMathJSONExprReturn 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")Operators
MathJSON.OperatorCategory — Module
OperatorCategoryModule containing the operator category enum. Use scoped access to avoid namespace pollution.
Example
cat = OperatorCategory.ARITHMETIC
cat isa OperatorCategory.T # trueMathJSON.OPERATORS — Constant
OPERATORS::Dict{Symbol, OperatorCategory.T}Dictionary mapping MathJSON operator symbols to their categories. Loaded from data/operators.json at module initialization.
MathJSON.JULIA_FUNCTIONS — Constant
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.
MathJSON.get_category — Function
get_category(op::Symbol) -> OperatorCategory.TReturn 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.UNKNOWNMathJSON.get_julia_function — Function
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) # nothingMathJSON.is_known_operator — Function
is_known_operator(op::Symbol) -> BoolReturn 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) # falseSymbolics.jl Integration
MathJSON.to_symbolics — Function
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)MathJSON.from_symbolics — Function
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)Errors
MathJSON.MathJSONParseError — Type
MathJSONParseError <: ExceptionException thrown when parsing invalid MathJSON input.
Fields
message::String: Description of the parse errorposition::Union{Nothing, Int}: Optional position in the input where error occurred
Example
throw(MathJSONParseError("Unexpected token", 42))MathJSON.UnsupportedConversionError — Type
UnsupportedConversionError <: ExceptionException 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"))