How SAX-style incremental parsing works
masterFor 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 keysis encountered.string(s): Called when a string valuesis encountered.number(n): Called when a number valuenis encountered.boolean(b): Called when a boolean valuebis encountered.null(): Called when anullvalue is encountered.
Parser Workflow:
- Initialize the parser with an input source and your callback table.
- Call
parsercontext.run()to begin parsing. - The parser will trigger callbacks as it traverses the JSON structure.
- 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()