Lunajson

repository·master·Indexed 41 days ago

https://github.com/grafi-tt/lunajson

A pure Lua JSON library providing a simple decoder and encoder alongside a high-performance SAX-style incremental parser. Designed to be dependency-free and optimized for speed, it includes functions like lunajson.decode and lunajson.encode for standard use, and lunajson.newparser and lunajson.newfileparser for processing large JSON files via callbacks.

Tokens
1.3K
Snippets
3
Records
6
Agent score
2%

What's inside Lunajson

  1. How SAX-style incremental parsing works

    master

    For large JSON files, Lunajson provides a SAX-style (Simple API for XML) parser that allows you to process data incrementally without loading the entire file into memory. You create a parser context using lunajson.newparser (for strings/functions) or lunajson.newfileparser (for files) and provide a saxtbl containing callback functions.

    The saxtbl Callbacks:

    • startobject(): Called when an object { begins.
    • endobject(): Called when an object } ends.
    • startarray(): Called when an array [ begins.
    • endarray(): Called when an array ] ends.
    • key(s): Called when an object key s is encountered.
    • string(s): Called when a string value s is encountered.
    • number(n): Called when a number value n is encountered.
    • boolean(b): Called when a boolean value b is encountered.
    • null(): Called when a null value is encountered.

    Parser Workflow:

    1. Initialize the parser with an input source and your callback table.
    2. Call parsercontext.run() to begin parsing.
    3. The parser will trigger callbacks as it traverses the JSON structure.
    4. Upon completion, run() moves the position to just after the end of the JSON.
    local lunajson = require 'lunajson'
    
    local saxtbl = {
      startobject = function() print("Start Object") end,
      key = function(k) print("Key: " .. k) end,
      string = function(s) print("String: " .. s) end,
      endobject = function() print("End Object") end
    }
    
    local parser = lunajson.newparser('{"a": "b"}', saxtbl)
    parser.run()
  2. Install Lunajson

    master

    You can install Lunajson using LuaRocks or by manual installation.

    Using LuaRocks:

    luarocks install lunajson

    Manual Installation: Download the source and copy the contents of the src/ directory into a location included in your package.path.

  3. Simple JSON decoding and encoding

    master

    For most use cases, use lunajson.decode to convert a JSON string into a Lua table and lunajson.encode to convert a Lua table into a JSON string.

    local lunajson = require 'lunajson'
    local jsonstr = '{"Hello":["lunajson",1.5]}'
    
    -- Decode string to table
    local t = lunajson.decode(jsonstr)
    print(t.Hello[2]) -- prints 1.5
    
    -- Encode table to string
    print(lunajson.encode(t)) -- prints {"Hello":["lunajson",1.5]}
    local lunajson = require 'lunajson'
    local jsonstr = '{"Hello":["lunajson",1.5]}'
    local t = lunajson.decode(jsonstr)
    print(t.Hello[2]) -- prints 1.5
    print(lunajson.encode(t)) -- prints {"Hello":["lunajson",1.5]}
  4. lunajson.decode(jsonstr, [pos, [nullv, [arraylen]]])

    master

    Decodes a JSON string into a Lua table.

    Parameters:

    • jsonstr: The JSON string to decode.
    • pos (optional): The starting position for decoding. If provided, the function returns the decoded value AND the position immediately after the end of the decoded JSON.
    • nullv (optional): A sentinel value. If specified, JSON null values will be decoded as this value. Otherwise, they are discarded.
    • arraylen (optional): A boolean. If true, the length of an array ary will be stored in ary[0]. This helps distinguish between empty arrays and empty objects.

    Returns:

    • The decoded value.
    • If pos was provided, the next position in the string.
  5. lunajson.newparser(input, saxtbl) and lunajson.newfileparser(filename, saxtbl)

    master

    Creates a SAX-style parser context.

    Parameters:

    • input / filename:
      • For newparser: A string to parse, or a function that returns the next chunk of data as a string (returns nil when finished).
      • For newfileparser: A filename to parse.
    • saxtbl: A table of callback functions (startobject, endobject, startarray, endarray, key, string, number, boolean, null).

    ParserContext Methods:

    • run(): Starts parsing. Moves position to after the JSON if successful; errors otherwise.
    • tellpos(): Returns the current byte position.
    • tryc(): Returns the byte at the current position as a number (does not advance position). Returns nil if end of input.
    • read(n): Returns an n-length string starting from the current position and advances the position by n.
  6. lunajson.encode(value, [nullv])

    master

    Encodes a Lua value into a JSON string.

    Parameters:

    • value: The Lua value (table, string, number, etc.) to encode.
    • nullv (optional): If specified, any Lua value equal to nullv will be encoded as JSON null.

    Table Encoding Rules:

    • Arrays: A table t is encoded as a JSON array if t[1] is present OR if a number is present at t[0]. If t[0] is present, its value is treated as the explicit length of the array (allowing for nil elements to be encoded as null). Otherwise, it scans from index 1 until the first nil is found.
    • Objects: If the table is not an array, it is treated as a JSON object. All keys must be strings.

    Errors:

    • Raises an error if keys are not strings (for objects) or if the table contains unsupported types (e.g., functions).