package core:encoding/json

⌘K
Ctrl+K
or
/

    Overview

    Encoding and decoding JSON in strict JSON, JSON5 and BitSquid variants.

    Using one of these Specifications.

    JSON
    	strict JSON; NUL bytes after the value are ignored
    JSON5
    	pure superset of JSON and valid JavaScript
    	https://json5.org/
    
    	* Object keys may be an ECMAScript 5.1 IdentifierName of ASCII letters, digits, `_` and `$`;
    	  Unicode letters and `\u` escapes are not supported.
    	* Objects may have a single trailing comma.
    	* Arrays may have a single trailing comma.
    	* Strings may be single quoted.
    	* Strings may span multiple lines by escaping new line characters.
    	* Strings may include character escapes
    	* Numbers may be hexadecimal.
    	* Numbers may have a leading or trailing decimal point.
    	* Numbers may be IEEE 754 positive infinity, negative infinity, and NaN.
    	* Numbers may begin with an explicit plus sign.
    	* Single and multi-line comments are allowed.
    	* Additional white space characters are allowed.
    
    MJSON
    	pure superset of JSON5, may not be valid JavaScript
    	https://bitsquid.blogspot.com/2009/10/simplified-json-notation.html
    
    	* All the same features as JSON5 plus extras.
    	* Assume an object definition at the root level (no need to surround entire file with { } );
    	  an empty document is an empty object.
    	* Commas are optional; a line break after a value acts as one, so no line may start with a comma.
    	* Quotes around object keys are optional if the keys are valid identifiers.
    	* : can be replaced with =
    

    External Examples 3 ¶

    The programs in odin-lang/examples about this package, and how many of its declarations each uses.

    Types

    Array ¶

    Array :: distinct [dynamic]Value

    Error ¶

    Error :: enum int {
    	None, 
    	EOF,                            // Not necessarily an error
    	// Tokenizing Errors
    	Illegal_Character, 
    	Invalid_Number, 
    	String_Not_Terminated, 
    	Invalid_String, 
    	Invalid_Rune, 
    	// Parsing Errors
    	Unexpected_Token, 
    	Expected_String_For_Object_Key, 
    	Duplicate_Object_Key, 
    	Expected_Colon_After_Key, 
    	Max_Depth_Exceeded, 
    	// Allocating Errors
    	Invalid_Allocator, 
    	Out_Of_Memory, 
    }

    Related Procedures With Returns

    Float ¶

    Float :: f64
    External examples json/load_json

    Marshal_Data_Error ¶

    Marshal_Data_Error :: enum int {
    	None, 
    	Unsupported_Type, 
    	Non_Finite_Float, // Infinity or NaN, which only JSON5 and MJSON can represent
    	Key_Needs_Quotes, 
    }

    Marshal_Options ¶

    Marshal_Options :: struct {
    	// output based on spec
    	spec:                             Specification,
    	// Use line breaks & tabs/spaces
    	pretty:                           bool,
    	// Use spaces for indentation instead of tabs
    	use_spaces:                       bool,
    	// Given use_spaces true, use this many spaces per indent level. 0 means 4 spaces.
    	spaces:                           int,
    	// Output unsigned integers, and non-negative `Integer`s in `unparse`, as hex (`0xff`) in JSON5 & MJSON
    	write_uint_as_hex:                bool,
    	// If spec is MJSON and this is true, then keys will be quoted.
    	// Otherwise each key must be a bare identifier, `[A-Za-z_][A-Za-z0-9_]*` other than
    	// `null`, `true`, `false`, `NaN` and `Infinity`, or marshal returns `.Key_Needs_Quotes`.
    	mjson_keys_use_quotes:            bool,
    	// If spec is MJSON and this is true, then use '=' as delimiter between
    	// keys and values, otherwise ':' is used.
    	mjson_keys_use_equal_sign:        bool,
    	// When outputting a map, sort the output by key.
    	// 
    	// NOTE: This will temp allocate and sort a list for each map.
    	sort_maps_by_key:                 bool,
    	// Output enum value's name instead of its underlying value.
    	// 
    	// NOTE: If a name isn't found it'll use the underlying value.
    	use_enum_names:                   bool,
    	// Output `null` for an infinity or NaN, as JavaScript's `JSON.stringify` does,
    	// rather than returning `.Non_Finite_Float` in JSON or writing `Infinity` or `NaN` in JSON5 and MJSON.
    	non_finite_as_null:               bool,
    	// Internal state
    	indentation:                      int,
    	mjson_skipped_first_braces_start: bool,
    	mjson_skipped_first_braces_end:   bool,
    	mjson_root_has_entries:           bool,
    	container_empty:                  bool,
    }

    Related Procedures With Parameters

    Match_Error ¶

    Match_Error :: enum int {
    	None, 
    	Invalid_Argument, 
    	Invalid_Type_For_Index, 
    	Invalid_Type_For_Key, 
    	Key_Not_Found, 
    	Out_Of_Bounds_Index, 
    }

    Match_Flag ¶

    Match_Flag :: enum int {
    	Ignore_Key_Not_Found, 
    	Allow_String_Indexing_By_Byte, 
    }

    Match_Flags ¶

    Match_Flags :: distinct bit_set[Match_Flag]

    Match_Key_Variant ¶

    Match_Key_Variant :: union #no_nil {
    	int, 
    	string, 
    }

    Object ¶

    Object :: distinct map[string]Value
    External examples json/load_json

    Parser ¶

    Parser :: struct {
    	tok:            Tokenizer,
    	prev_token:     Token,
    	curr_token:     Token,
    	curr_token_err: Error,
    	spec:           Specification,
    	allocator:      runtime.Allocator,
    	parse_integers: bool,
    	depth:          int,
    	union_attempt:  Union_Attempt,
    	flags:          Unmarshal_Flags,
    }

    Related Procedures With Parameters

    Related Procedures With Returns

    Pos ¶

    Pos :: struct {
    	offset: int,
    	line:   int,
    	column: int,
    }

    Register_User_Marshaler_Error ¶

    Register_User_Marshaler_Error :: enum int {
    	None, 
    	No_User_Marshaler, 
    	Marshaler_Previously_Found, 
    }

    Register_User_Unmarshaler_Error ¶

    Register_User_Unmarshaler_Error :: enum int {
    	None, 
    	No_User_Unmarshaler, 
    	Unmarshaler_Previously_Found, 
    }

    Specification ¶

    Specification :: enum int {
    	JSON, 
    	JSON5,            // https://json5.org/
    	SJSON,            // https://bitsquid.blogspot.com/2009/10/simplified-json-notation.html
    	Bitsquid = SJSON, 
    	MJSON    = SJSON, 
    }

    Related Procedures With Parameters

    Related Constants

    Token ¶

    Token :: struct {
    	using pos: Pos,
    	kind: Token_Kind,
    	text: string,
    }

    Related Procedures With Parameters

    Related Procedures With Returns

    Fields Through using (3)

    From using pos: Pos

    Token_Kind ¶

    Token_Kind :: enum int {
    	Invalid, 
    	EOF, 
    	Null, 
    	False, 
    	True, 
    	Infinity, 
    	NaN, 
    	Ident, 
    	Integer, 
    	Float, 
    	String, 
    	Colon, 
    	Comma, 
    	Open_Brace, 
    	Close_Brace, 
    	Open_Bracket, 
    	Close_Bracket, 
    }

    Related Procedures With Parameters

    Tokenizer ¶

    Tokenizer :: struct {
    	using pos:        Pos,
    	data:             string,
    	r:                rune,
    	// current rune
    	w:                int,
    	// current rune width in bytes
    	curr_line_offset: int,
    	spec:             Specification,
    	parse_integers:   bool,
    	insert_comma:     bool,
    	validated:        bool,
    }

    Related Procedures With Parameters

    Fields Through using (3)

    From using pos: Pos

    Union_Attempt ¶

    Union_Attempt :: enum u8 {
    	None, 
    	Strict, 
    	Lenient, 
    }

    Unknown_Field_Error ¶

    Unknown_Field_Error :: struct {
    	id:    typeid,
    	token: Token,
    	field: string,
    }
     

    A key that matches no field of the struct id, returned only with .Disallow_Unknown_Fields

    Unmarshal_Data_Error ¶

    Unmarshal_Data_Error :: enum int {
    	Invalid_Data, 
    	Invalid_Parameter, 
    	Non_Pointer_Parameter, 
    	Multiple_Use_Field, 
    }

    Unmarshal_Flag ¶

    Unmarshal_Flag :: enum int {
    	// Skips the `is_valid` pass over the input. Syntax errors are reported
    	// where they are reached instead, as specific `Error` values, and the same input is accepted.
    	Skip_Validation, 
    	// Count an object's entries and reserve the map once rather than growing it
    	Reserve_Maps, 
    	// Accept duplicate keys in an object (struct fields, map keys, enumerated array indices) rather
    	// than returning `.Multiple_Use_Field`. Only the last occurrence is unmarshalled; the object's
    	// keys are scanned first to find it.
    	Allow_Duplicate_Fields, 
    	// Return an `Unknown_Field_Error` for a key that matches no struct field, rather than skipping it
    	Disallow_Unknown_Fields, 
    	// Require a fixed-length array, enumerated array, or complex number to be given every element,
    	// rather than leaving the missing trailing elements unchanged
    	Disallow_Short_Arrays, 
    	// Return an `Unsupported_Type_Error` for an integer, or an integral float, that doesn't fit its integer type,
    	// rather than wrapping it as a conversion would
    	Disallow_Integer_Wrap, 
    }

    Unmarshal_Flags ¶

    Unmarshal_Flags :: distinct bit_set[Unmarshal_Flag]

    Related Procedures With Parameters

    Unparse_Error ¶

    Unparse_Error :: union {
    	io.Error, 
    	runtime.Allocator_Error, 
    	Marshal_Data_Error, 
    }

    Related Procedures With Returns

    Unsupported_Type_Error ¶

    Unsupported_Type_Error :: struct {
    	id:    typeid,
    	token: Token,
    	field: string,
    }
     

    field is the JSON key of the innermost struct field whose value could not be unmarshalled, and id is that field's type; outside a struct field, field is empty. field is allocated with the unmarshal allocator: free it with delete(err.field, allocator). A User_Unmarshaler that returns this error with field set must allocate it with p.allocator.

    User_Marshaler ¶

    User_Marshaler :: proc(w: io.Stream, v: any, opt: ^Marshal_Options) -> Marshal_Error

    User_Unmarshaler ¶

    User_Unmarshaler :: proc(p: ^Parser, v: any) -> Unmarshal_Error

    Value ¶

    Value :: union {
    	Null, 
    	i64, 
    	f64, 
    	bool, 
    	string, 
    	Array, 
    	Object, 
    }

    Related Procedures With Parameters

    Related Procedures With Returns

    Constants

    DEFAULT_SPECIFICATION ¶

    DEFAULT_SPECIFICATION :: Specification.JSON5

    MAX_DEPTH ¶

    MAX_DEPTH :: #config(JSON_MAX_DEPTH, 128)
    -define:JSON_MAX_DEPTH=128

    Variables

    This section is empty.

    Procedures

    advance_token ¶

    advance_token :: proc(p: ^Parser) -> (Token, Error) {…}

    allow_token ¶

    @(require_results)
    allow_token :: proc(p: ^Parser, kind: Token_Kind) -> bool {…}

    clone_string ¶

    @(require_results)
    clone_string :: proc(
    	s:         string, 
    	allocator: runtime.Allocator, 
    	loc := #caller_location, 
    ) -> (str: string, err: Error) {…}

    clone_value ¶

    @(require_results)
    clone_value :: proc(value: Value, allocator := context.allocator) -> Value {…}

    destroy_value ¶

    destroy_value :: proc(value: Value, allocator := context.allocator, loc := #caller_location) {…}
    External examples json/load_json

    expect_token ¶

    @(require_results)
    expect_token :: proc(p: ^Parser, kind: Token_Kind) -> Error {…}

    get_token ¶

    @(require_results)
    get_token :: proc(t: ^Tokenizer) -> (token: Token, err: Error) {…}

    is_valid ¶

    @(require_results)
    is_valid :: proc(
    	data:           []u8, 
    	spec:           Specification = DEFAULT_SPECIFICATION, 
    	parse_integers: bool = false, 
    ) -> bool {…}
     

    NOTE(bill): is_valid will not check for duplicate keys

    is_valid_number ¶

    @(require_results)
    is_valid_number :: proc(str: string, spec: Specification) -> bool {…}

    is_valid_string_literal ¶

    @(require_results)
    is_valid_string_literal :: proc(str: string, spec: Specification) -> bool {…}

    make_parser_from_bytes ¶

    @(require_results)
    make_parser_from_bytes :: proc(
    	data:           []u8, 
    	spec:           Specification = DEFAULT_SPECIFICATION, 
    	parse_integers: bool = false, 
    	allocator := context.allocator, 
    ) -> Parser {…}

    make_parser_from_string ¶

    @(require_results)
    make_parser_from_string :: proc(
    	data:           string, 
    	spec:           Specification = DEFAULT_SPECIFICATION, 
    	parse_integers: bool = false, 
    	allocator := context.allocator, 
    ) -> Parser {…}

    make_tokenizer ¶

    @(require_results)
    make_tokenizer :: proc(
    	data:           string, 
    	spec:           Specification = DEFAULT_SPECIFICATION, 
    	parse_integers: bool = false, 
    ) -> Tokenizer {…}

    marshal ¶

    @(require_results)
    marshal :: proc(
    	v:         any, 
    	opt:       Marshal_Options = {}, 
    	allocator := context.allocator, 
    	loc := #caller_location, 
    ) -> (data: []u8, err: Marshal_Error) {…}
     

    Struct field tags: json:"name" sets the key, json:"-" skips the field, and omitempty after the name (json:",omitempty" keeps the field's own name) leaves the field out when it is nil or empty: a nil pointer, procedure, any, typeid or union, or an empty string, slice, dynamic array, map or bit_set. Numbers, bools, enums, fixed arrays and structs are always written. With pretty, JSON5 and MJSON write a jsoncomment:"text" tag above its field as // lines.

    External examples json/write_json_marshal

    marshal_to_builder ¶

    marshal_to_builder :: proc(
    	b:   ^strings.Builder, 
    	v:   any, 
    	opt: Marshal_Options = {}, 
    ) -> Marshal_Error {…}

    marshal_to_writer ¶

    marshal_to_writer :: proc(
    	w:   io.Stream, 
    	v:   any, 
    	opt: Marshal_Options = {}, 
    ) -> (err: Marshal_Error) {…}

    match ¶

    @(require_results)
    match :: proc(
    	value: Value, 
    	args:  ..Match_Key_Variant, 
    	flags: Match_Flags = nil, 
    ) -> (found: Value, err: Match_Error) {…}

    next_rune ¶

    next_rune :: proc(t: ^Tokenizer) -> rune {…}

    parse_array ¶

    @(require_results)
    parse_array :: proc(p: ^Parser, loc := #caller_location) -> (value: Value, err: Error) {…}

    parse_bytes ¶

    @(require_results)
    parse_bytes :: proc(
    	data:           []u8, 
    	spec:           Specification = DEFAULT_SPECIFICATION, 
    	parse_integers: bool = false, 
    	allocator := context.allocator, 
    	loc := #caller_location, 
    ) -> (Value, Error) {…}

    parse_colon ¶

    @(require_results)
    parse_colon :: proc(p: ^Parser) -> (err: Error) {…}

    parse_comma ¶

    @(require_results)
    parse_comma :: proc(p: ^Parser) -> (do_break: bool) {…}

    parse_object ¶

    @(require_results)
    parse_object :: proc(p: ^Parser, loc := #caller_location) -> (value: Value, err: Error) {…}

    parse_object_body ¶

    @(require_results)
    parse_object_body :: proc(
    	p:         ^Parser, 
    	end_token: Token_Kind, 
    	loc := #caller_location, 
    ) -> (obj: Object, err: Error) {…}

    parse_object_key ¶

    @(require_results)
    parse_object_key :: proc(
    	p:             ^Parser, 
    	key_allocator: runtime.Allocator, 
    	loc := #caller_location, 
    ) -> (key: string, err: Error) {…}

    parse_string ¶

    @(require_results)
    parse_string :: proc(
    	data:           string, 
    	spec:           Specification = DEFAULT_SPECIFICATION, 
    	parse_integers: bool = false, 
    	allocator := context.allocator, 
    	loc := #caller_location, 
    ) -> (Value, Error) {…}

    parse_value ¶

    @(require_results)
    parse_value :: proc(p: ^Parser, loc := #caller_location) -> (value: Value, err: Error) {…}

    register_user_marshaler ¶

    register_user_marshaler :: proc(
    	id:        typeid, 
    	marshaler: User_Marshaler, 
    ) -> Register_User_Marshaler_Error {…}
     

    Registers a user-defined marshaler for a specific typeid

    Inputs:

    • id The typeid of the custom type.
    • marshaler The User_Marshaler function for the custom type.

    Returns:
    A Register_User_Marshaler_Error value indicating the success or failure of the operation.

    WARNING: set_user_marshalers must be called before using this procedure.

    register_user_unmarshaler ¶

    register_user_unmarshaler :: proc(
    	id:          typeid, 
    	unmarshaler: User_Unmarshaler, 
    ) -> Register_User_Unmarshaler_Error {…}
     

    Registers a user-defined unmarshaler for a specific typeid.

    WARNING: set_user_unmarshalers must be called before using this procedure.

    NOTE: With SJSON, a document whose root object has no braces (a = 1) is unmarshalled key by key, so an unmarshaler registered for the root type is not called for it.

    Inputs:

    • id The typeid of the custom type.
    • unmarshaler The User_Unmarshaler function for the custom type.
    Example:
    import "core:fmt"
    import "core:encoding/json"
    import "core:strconv"
    
    // Custom Unmarshaler for `int`
    some_unmarshaler :: proc(p: ^json.Parser, v: any) -> json.Unmarshal_Error {
    	token := p.curr_token.text
    	i, ok := strconv.parse_i64_of_base(token, 2)
    	if !ok {
    		return .Invalid_Data
    	}
    
    	(^int)(v.data)^ = int(i)
    
    	json.advance_token(p)
    	return nil
    }
    
    register_user_unmarshaler_example :: proc() {
    	// Ensure the `json._user_unmarshalers` map is initialized.
    	json.set_user_unmarshalers(new(map[typeid]json.User_Unmarshaler))
    	reg_err := json.register_user_unmarshaler(typeid_of(int), some_unmarshaler)
    	assert(reg_err == .None)
    
    	data := `{"value":101010}`
    	SomeType :: struct {
    		value: int,
    	}
    	y: SomeType
    
    	unmarshal_err := json.unmarshal(transmute([]byte)data, &y)
    	fmt.println(y, unmarshal_err)
    }
    
    Output:
    SomeType{value = 42} nil
    

    set_user_marshalers ¶

    set_user_marshalers :: proc(m: ^map[typeid]User_Marshaler) {…}
     

    Sets user-defined marshalers for custom json marshaling of specific types

    Inputs:

    • m A pointer to a map of typeids to User_Marshaler procs.

    NOTE: Must be called before using register_user_marshaler.

    set_user_unmarshalers ¶

    set_user_unmarshalers :: proc(m: ^map[typeid]User_Unmarshaler) {…}
     

    Sets user-defined unmarshalers for custom json unmarshaling of specific types

    Inputs:

    • m A pointer to a map of typeids to User_Unmarshaler procs.

    NOTE: Must be called before using register_user_unmarshaler.

    token_end_pos ¶

    @(require_results)
    token_end_pos :: proc(tok: Token) -> Pos {…}

    unmarshal ¶

    unmarshal :: proc(
    	data:      []u8, 
    	ptr:       ^$T, 
    	spec:      Specification = DEFAULT_SPECIFICATION, 
    	allocator := context.allocator, 
    	flags:     Unmarshal_Flags = Unmarshal_Flags{}, 
    ) -> Unmarshal_Error {…}
    External examples json/load_json_unmarshal

    unmarshal_any ¶

    unmarshal_any :: proc(
    	data:      []u8, 
    	v:         any, 
    	spec:      Specification = DEFAULT_SPECIFICATION, 
    	allocator := context.allocator, 
    	flags:     Unmarshal_Flags = Unmarshal_Flags{}, 
    ) -> Unmarshal_Error {…}

    unmarshal_string ¶

    unmarshal_string :: proc(
    	data:      string, 
    	ptr:       ^$T, 
    	spec:      Specification = DEFAULT_SPECIFICATION, 
    	allocator := context.allocator, 
    	flags:     Unmarshal_Flags = Unmarshal_Flags{}, 
    ) -> Unmarshal_Error {…}

    unmarshal_value ¶

    unmarshal_value :: proc(
    	p:     ^Parser, 
    	v:     any, 
    	flags: Unmarshal_Flags = Unmarshal_Flags{}, 
    ) -> (err: Unmarshal_Error) {…}

    unparse ¶

    @(require_results)
    unparse :: proc(
    	v:         Value, 
    	opt:       Marshal_Options = {}, 
    	allocator := context.allocator, 
    	loc := #caller_location, 
    ) -> (data: string, err: Unparse_Error) {…}
     

    Formats value v back into an equivalent JSON string, and returns the result as a string.

    Allocates the result using the provided allocator (caller must free the result).

    unparse_to_builder ¶

    @(require_results)
    unparse_to_builder :: proc(
    	b:   ^strings.Builder, 
    	v:   Value, 
    	opt: Marshal_Options = {}, 
    ) -> Unparse_Error {…}
     

    Formats value v back into an equivalent JSON string, and writes it into b.

    unparse_to_writer ¶

    @(require_results)
    unparse_to_writer :: proc(
    	w:     io.Stream, 
    	value: Value, 
    	opt:   Marshal_Options = {}, 
    ) -> Unparse_Error {…}
     

    Formats value v back into an equivalent JSON string, and writes it into w.

    unquote_string ¶

    @(require_results)
    unquote_string :: proc(
    	token:     Token, 
    	spec:      Specification, 
    	allocator := context.allocator, 
    	loc := #caller_location, 
    ) -> (value: string, err: Error) {…}
     

    IMPORTANT NOTE(bill): unquote_string assumes a mostly valid string

    validate_array ¶

    @(require_results)
    validate_array :: proc(p: ^Parser) -> bool {…}

    validate_object ¶

    @(require_results)
    validate_object :: proc(p: ^Parser) -> bool {…}

    validate_object_body ¶

    @(require_results)
    validate_object_body :: proc(p: ^Parser, end_token: Token_Kind) -> bool {…}

    validate_object_key ¶

    @(require_results)
    validate_object_key :: proc(p: ^Parser) -> bool {…}

    validate_value ¶

    @(require_results)
    validate_value :: proc(p: ^Parser) -> bool {…}

    write_json_escaped_rune ¶

    write_json_escaped_rune :: proc(w: io.Stream, r: rune) -> io.Error {…}
     

    Writes rune r to w, encoding and escaping it, according to the syntax rules of JSON.

    Remarks

    The bytes written to w are the UTF-8 encoded result string after conversion.

    This is a specialized version of io.write_escaped_rune which uses a different ruleset.

    Control characters recognized by JSON (\b, \f, \n, \r, \t) are escaped as such. Other runes are escaped only if they represent an unprintable or otherwise problematic character, such as \u0300.

    write_quoted_json_string ¶

    write_quoted_json_string :: proc(w: io.Stream, str: string) -> io.Error {…}
     

    Writes string str to w, encoding and escaping the string's runes, according to the syntax rules of JSON.

    Remarks

    The bytes written to w are the UTF-8 encoded result string after conversion.

    This is a specialized version of io.write_quoted_string which uses a different ruleset.

    The encoded string is always enclosed in double-quotes (").

    Control characters recognized by JSON (\b, \f, \n, \r, \t) are escaped as such. Other runes are escaped only if they represent an unprintable or otherwise problematic character, such as \u0300.

    If the input string contains a UTF-8 encoding error, then its contents cannot be preserved exactly, and invalid UTF-8 bytes are represented with the Unicode replacement character.

    Procedure Groups

    parse ¶

    parse :: proc{
    	parse_bytes,
    	parse_string,
    }
    
    External examples json/load_json

    `#config` values

    Source Files

    Generation Information

    Generated with odin version dev-2026-11 (vendor "odin") Windows_amd64 @ 2026-11-18 21:05:19.828955300 +0000 UTC