JSON high-performance bidirectional conversion framework. This module is a fork of the dkjson library by David Kolf, removing LPeg support and registration of the _G.json
global.
On Wikia, it serves as a polyfill for the mw.text.jsonEncode
and mw.text.jsonDecode
PHP interfaces available in Scribunto core. Json is able to perform within one order of magnitude (20%) to its PHP counterpart, while also supporting multiline comments.
JSON is a data serialisation format by the IETF and JS developer Douglas Crockford that maps data in objects consisting of arrays (key-value pairs) and lists (ordered element collections).
The json.encode
function will use two spaces for indentation when it is enabled, matching the behaviour of mw.text.jsonDecode
. If you need to output JSON with four spaces per indent, use string.gsub
and parentheses - (json.encode({json.null}):gsub('\n( +)','\n%1%1'))
.
The json.decode
function accepts optional arguments to enable the bidirectional processing of any JSON data. The RFC 8259 JSON specification does not support JavaScript's inline and multiline comments, but these are stripped gracefully in the parser anyway along with any whitespace.
Documentation
Package items
json.version
(member)- Version of the JSON library.
json.encode(value, state)
(function)- JSON serialiser in pure Lua for data objects.
- Parameters:
value
Lua upvalue to serialise into JSON. A table can only use strings and numbers as keys and its values have to be valid objects as well. (table|string|number|boolean|nil)state
Serialiser state/option configuration. (table; optional)state.indent
Whether the serialised string will be formatted with newlines and indentations. If not, the encoded JSON will be compressed to one line. (boolean; optional)state.keyorder
Array that specifies the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. (table; optional)state.level
Initial level of indentation used whenstate.indent
is enabled. For each level, four spaces are added. Default:0
. (number; optional)state.bufferlen
The target length of the buffer array, to validate against the true buffer length. (number; optional)state.tables
Internal set for reference cycles. It is written to by the table scanning utilities and has every table that is currently processed attached as a key. The set key becomes temporary when the table value is absent. (number; optional)state.exception
Custom exception handler, called when the encoder cannot encode a given value. Seejson.encode_exception
for a example function and the handler parameter description. (function; optional)
- Error: Exceptions for invalid data types, reference cycles in tables or custom encoding failures thrown by any
__tojson
metafields. (string; line 729) - Returns: JSON string representation of the data object, or boolean for
state.bufferlen
validity. The Lua values for ECMAScript'sInf
andNaN
are encoded asnull
per the JSON specification. The tables within the object are only serialised as arrays if the following rules apply:- All table keys are numerical non-zero integers.
- More than half of the array elements are non-nil values IF the array size is greater than 10.
- (string|number)
json.decode(str, position, null, mt)
(function)- JSON parser in pure Lua for valid JSON strings. Converts a JSON string representation of Lua data into the corresponding Lua table or primitive.
- Parameters:
str
JSON string representation of value. (string)position
Internal argument for start character position. Default:1
- start of string. (string; optional)null
Value to use for JSON'snull
value. Acceptsjson.null
for internal bidirectionality. Default:nil
. (string|table; optional)mt
Assign metatables to objects for internal bidirectionality. (boolean; optional)
- Error: Exception with character position upon parsing failure. (string; line 760; optional)
- Returns: Deserialised Lua data from JSON string.
json.quote(value)
(function)- JSON double quote escape generator from UTF-8 strings.
- Parameter:
value
Unquoted string representation of key. (string) - Returns: Double quote with Unicode backslash escapes.
- See also: github:douglascrockford/JSON-js/blob/2a76286/json2.js#L168
json.add_newline(state)
(function)- Newline insertion utility for
__tojson
metafields. Whenstate.indent
is set, this function add a newline tostate.buffer
and adds spaces according tostate.level
. - Parameter:
state
State tracking fromjson.encode
. (table) json.encode_exception(reason, value, state, defaultmessage)
(function)- Exception encoder for debugging malformed input data. This function is passed to
state.exception
injson.encode
. Instead of raising an error, this function encodes the error message as a string. - Parameters:
json.null
(table)- Lua representation of JSON null object. This function is useful for bidirectionality in
json.decode
. - Field:
__tojson
Returns'null'
when encoding. (function)
JSON serialisation metafields
The json.encode
method supports a series of metafields used in the configuration of serialisation behaviour when encoding Lua.
value.__jsonorder
(member; string)- Serialisation order configuration. Overwrites the
json.encode
keyorder
option for any specific table or subtable it is attached to. If a key is not present in the order array, it is serialised after the listed keys. value.__jsontype
(member; string)- Serialisation object class name. Defines which
- a Lua table should be rendered as a JSON object or a JSON array. Accepts a value of
"object"
or"array"
. This value is only tested for empty tables. Default:"array"
. value.__tojson(state)
(function)- Serialisation handler function. This function can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned.
- Parameters:
state
State tracking for JSON serialisation. (table)state.buffer
Buffer array containing the string nodes generated byjson.encode
. (table)state.bufferlen
Buffer length, used for tracking. (table)
- Returns:
- JSON representation of the Lua item as a string, or
true
when the handler inserts data directly into the buffer. If the handler is throwing an exception message, this return value is set tonil
. (string|boolean|nil) - Error message describing serialisation failure, to be thrown in
json.encode
. (string; optional)
- JSON representation of the Lua item as a string, or