### dkjson Version Source: https://dkolf.de/dkjson-lua/documentation Access the `json.version` field to get the current version of the dkjson module. ```lua print(json.version) ``` -------------------------------- ### JSON Decoding Source: https://dkolf.de/dkjson-lua/documentation Decodes a JSON string into a Lua object. Allows specifying the starting position and a custom value for null. ```APIDOC ## json.decode (string [, position [, null]]) ### Description Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. ### Return Value The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. ### Custom Metatables Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax ```lua json.decode (string, position, null, objectmeta, arraymeta) ``` To prevent the assigning of metatables pass `nil`: ```lua json.decode (string, position, null, nil) ``` ``` -------------------------------- ### Decode JSON String to Lua Object Source: https://dkolf.de/dkjson-lua/documentation Decodes a JSON string into a Lua object. Optionally specify the starting position and a custom value for null. Can also accept custom metatables for decoded objects. ```lua json.decode (string [, position [, null]]) ``` ```lua json.decode (string, position, null, objectmeta, arraymeta) ``` ```lua json.decode (string, position, null, nil) ``` -------------------------------- ### Import dkjson Module Source: https://dkolf.de/dkjson-lua/documentation Import the dkjson module using require. If require is not available, configure it to register globally. ```lua json = require ("dkjson") ``` -------------------------------- ### Load Standard dkjson Module Source: https://dkolf.de/dkjson-lua/documentation Require the standard `dkjson` module without LPeg support. The original module table remains unchanged. ```lua json = require "dkjson" ``` -------------------------------- ### Load dkjson with LPeg Support Source: https://dkolf.de/dkjson-lua/documentation Call `json.use_lpeg()` to load the LPeg module and replace the default `decode` function with an LPeg-based version. This can significantly improve decoding performance. ```lua json = require "dkjson".use_lpeg() ``` -------------------------------- ### json.use_lpeg() Source: https://dkolf.de/dkjson-lua/documentation Enables LPeg support for the JSON decoding function to improve performance. ```APIDOC ## json.use_lpeg() ### Description Require the LPeg module and return a copy of the module table where the decode function is replaced by a version that uses LPeg for faster processing. ### Request Example json = require "dkjson".use_lpeg() ### Response - **module** (table) - A copy of the module table with LPeg-based decoding enabled. ``` -------------------------------- ### json.using_lpeg Source: https://dkolf.de/dkjson-lua/documentation A boolean flag indicating if the current module instance is using LPeg. ```APIDOC ## json.using_lpeg ### Description This variable is set to true in the copy of the module table that uses LPeg support. ### Response - **using_lpeg** (boolean) - Returns true if LPeg is active, otherwise nil or false. ``` -------------------------------- ### Enable LPeg support for JSON decoding in Lua Source: https://dkolf.de/dkjson-lua/readme-2.8.txt Require the LPeg module and return a modified module table where the `decode` function is replaced by an LPeg-based version for significant speed improvements. The original module table remains unchanged. ```lua json = require "dkjson".use_lpeg() ``` -------------------------------- ### Metatable Extensions Source: https://dkolf.de/dkjson-lua/documentation Defines custom behaviors for Lua tables when interacting with dkjson. ```APIDOC ## `.__jsonorder` ### Description `__jsonorder` can overwrite the `keyorder` for a specific table. ## `.__jsontype` ### Description `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). ## `.__tojson (self, state)` ### Description You can provide your own `__tojson` function in a metatable. In this function you 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. ``` -------------------------------- ### Custom Key Ordering for Encoding Source: https://dkolf.de/dkjson-lua/documentation Use the `keyorder` field in the state table to specify the desired order of keys in the encoded JSON output. Keys not present in `keyorder` will appear after the sorted keys. ```lua json.encode (object, { keyorder = {"key1", "key2"} }) ``` -------------------------------- ### Utility Functions and Constants Source: https://dkolf.de/dkjson-lua/documentation Provides constants and utility functions for JSON manipulation. ```APIDOC ## `json.null` ### Description You can use this value for setting explicit `null` values. ## `json.version` ### Description Set to `"dkjson 2.8"`. ## `json.quotestring (string)` ### Description Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. ## `json.addnewline (state)` ### Description When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. ## `json.encodeexception (reason, value, state, defaultmessage)` ### Description This function can be used as value to the `exception` option. Instead of raising an error this function encodes the error message as a string. This can help to debug malformed input data. ### Example ```lua x = json.encode(value, { exception = json.encodeexception }) ``` ``` -------------------------------- ### Pretty-Printing JSON Output Source: https://dkolf.de/dkjson-lua/documentation Set the `indent` field to true in the state table to generate a JSON string with newlines and indentation for better readability. ```lua json.encode (object, { indent = true }) ``` -------------------------------- ### Access original dkjson module in Lua Source: https://dkolf.de/dkjson-lua/readme-2.8.txt When LPeg support is enabled via `use_lpeg()`, this is how you can still access the original module table without LPeg support. ```lua json = require "dkjson" ``` -------------------------------- ### Decode JSON with custom metatables Source: https://dkolf.de/dkjson-lua/readme-2.8.txt Provides custom metatables for decoded arrays and objects, or disables them by passing nil. ```lua json.decode (string, position, null, objectmeta, arraymeta) ``` ```lua json.decode (string, position, null, nil) ``` -------------------------------- ### Add Newline and Indentation Source: https://dkolf.de/dkjson-lua/documentation The `json.addnewline` function is used internally when `state.indent` is enabled to add appropriate newlines and spacing based on the current indentation level. ```lua json.addnewline (state) ``` -------------------------------- ### Custom JSON Encoding with `__tojson` Source: https://dkolf.de/dkjson-lua/documentation Implement a `__tojson` function in a metatable to control how a specific object is serialized to JSON. This function can directly add to the buffer or return a string. ```lua function my_object:__tojson (state) -- custom encoding logic here return true -- or return a string end ``` -------------------------------- ### JSON Encoding Source: https://dkolf.de/dkjson-lua/documentation Encodes a Lua object into a JSON string. Supports custom states for indentation, key ordering, and error handling. ```APIDOC ## json.encode (object [, state]) ### Description Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: * `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. * `keyorder` `keyorder` is an array to specify 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. * `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. * `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. * `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. * `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. * `exception` When `exception` is given, it will be called whenever the encoder cannot encode a given value. The parameters are `reason`, `value`, `state` and `defaultmessage`. `reason` is either `"reference cycle"`, `"custom encoder failed"` or `"unsupported type"`. `value` is the original value that caused the exception, `state` is this state table, `defaultmessage` is the message of the error that would usually be raised. You can either return `true` and add directly to the buffer or you can return the string directly. To keep raising an error return `nil` and the desired error message. An example implementation for an exception function is given in `json.encodeexception`. ### Return Value When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. ``` -------------------------------- ### JSON Decoding Source: https://dkolf.de/dkjson-lua/readme-2.8.txt Decodes a JSON string into a Lua object. Allows customization of null value representation and metatable assignment. ```APIDOC ## json.decode (string [, position [, null]]) ### Description Decode `string` starting at `position` or at 1 if `position` was omitted. Allows custom metatables and null value representation. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **string** (string) - The JSON string to decode. - **position** (number, optional) - The starting position in the string to begin decoding. Defaults to 1. - **null** (any, optional) - The value to return for JSON null values. Defaults to `nil`. - **objectmeta** (table, optional) - A metatable to assign to decoded JSON objects. If `nil`, no metatable is assigned. - **arraymeta** (table, optional) - A metatable to assign to decoded JSON arrays. If `nil`, no metatable is assigned. ### Request Example ```lua local json = require("dkjson") local json_string = '{"name":"Jane Doe","age":28,"isStudent":true}' local data, next_pos, err = json.decode(json_string) if data then print(data.name, data.age, data.isStudent) print("Next position:", next_pos) else print("Error decoding JSON:", err) end local custom_null_string = '[1, null, 3]' local decoded_with_custom_null = json.decode(custom_null_string, 1, json.null) print(decoded_with_custom_null[2]) -- Will print the json.null value ``` ### Response #### Success Response (200) - **object** (any) - The decoded Lua object. - **position** (number) - The position of the next character in the string that does not belong to the decoded object. - **error message** (string) - An error message if decoding failed, otherwise `nil`. ``` -------------------------------- ### JSON Encoding Source: https://dkolf.de/dkjson-lua/readme-2.8.txt Encodes a Lua object into a JSON string. Supports custom encoding, key ordering, and indentation. ```APIDOC ## json.encode (object [, state]) ### Description Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **object** (table | string | number | boolean | nil | json.null | object with `__tojson`) - The Lua object to encode. - **state** (table, optional) - A table with configuration options for encoding: - **indent** (boolean) - If true, the output string will contain newlines and indentations. Otherwise, it will be a single line. - **keyorder** (array) - An array specifying the desired order of keys in the encoded output. Keys not present in this array will be appended after the sorted keys. - **level** (number) - The initial indentation level. Each level adds two spaces. Defaults to 0. - **buffer** (array) - An array to store the resulting strings for concatenation. If not provided, the function creates and returns a concatenated string. - **bufferlen** (number) - The index of the last element in the `buffer` array. - **tables** (set) - A set used internally to detect reference cycles. It's created temporarily if not provided. - **exception** (function) - A callback function to handle encoding errors. It receives `reason`, `value`, `state`, and `defaultmessage` as arguments. ### Request Example ```lua local json = require("dkjson") local data = { name = "John Doe", age = 30, isStudent = false } local json_string = json.encode(data) print(json_string) local pretty_data = { items = { 1, 2, 3 }, settings = { enabled = true } } local pretty_json = json.encode(pretty_data, { indent = true }) print(pretty_json) ``` ### Response #### Success Response (200) - **return value** (string | boolean) - If `state.buffer` was provided, returns `true` on success. Otherwise, returns the JSON encoded string. ``` -------------------------------- ### Custom Exception Handling during Encoding Source: https://dkolf.de/dkjson-lua/documentation Provide an `exception` function in the state table to handle encoding errors gracefully. The `json.encodeexception` function can be used to encode error messages as strings instead of raising errors. ```lua x = json.encode(value, { exception = json.encodeexception }) ``` -------------------------------- ### Define Custom JSON Type for Tables Source: https://dkolf.de/dkjson-lua/documentation Use the `__jsontype` metatable field to specify whether an empty table should be treated as an 'array' or an 'object' during encoding/decoding. ```lua local my_object_meta = { __jsontype = "object" } ``` ```lua local my_array_meta = { __jsontype = "array" } ``` -------------------------------- ### json.encodeexception Source: https://dkolf.de/dkjson-lua/readme-2.8.txt A function used as an exception handler during JSON encoding to return error messages as strings instead of raising errors. ```APIDOC ## json.encodeexception ### Description This function can be used as a value for the 'exception' option in `json.encode`. It encodes the error message as a string instead of raising a Lua error, which is useful for debugging malformed input data. ### Usage Example ```lua x = json.encode(value, { exception = json.encodeexception }) ``` ``` -------------------------------- ### Custom Metatable Fields Source: https://dkolf.de/dkjson-lua/readme-2.8.txt Defines custom fields that can be used within metatables for decoded JSON objects. ```APIDOC ## Metatable Customization ### Description Custom fields can be added to metatables of decoded Lua tables to influence their behavior or representation. ### Fields #### `.__jsonorder` - **Description**: Overwrites the `keyorder` option for a specific table during encoding. #### `.__jsontype` - **Description**: Can be either `"array"` or `"object"`. This value is checked for empty tables to determine their default type. The default for empty tables is `"array"`. #### `.__tojson (self, state)` - **Description**: A custom function that can be provided in a metatable. This function is called during JSON encoding. It can directly add to the `state.buffer` and return `true`, or return a string representation of the object. On errors, it should return `nil` and an error message. ``` -------------------------------- ### Encode Lua table to JSON string Source: https://dkolf.de/dkjson-lua Use `json.encode` to convert a Lua table into a JSON formatted string. Set `indent = true` for pretty-printing. Requires `require("dkjson")`. ```lua local json = require ("dkjson") local tbl = { animals = { "dog", "cat", "aardvark" }, instruments = { "violin", "trombone", "theremin" }, bugs = json.null, trees = nil } local str = json.encode (tbl, { indent = true }) print (str) ``` -------------------------------- ### Explicit Null Value Source: https://dkolf.de/dkjson-lua/documentation Use `json.null` to represent explicit null values in Lua when encoding or decoding JSON. ```lua local data = { key = json.null } ``` -------------------------------- ### Encode Lua Object to JSON String Source: https://dkolf.de/dkjson-lua/documentation Encodes a Lua object into a JSON string. Supports custom encoding states for indentation and key ordering. Raises an error for invalid types or reference cycles. ```lua json.encode (object [, state]) ``` -------------------------------- ### Quote String for JSON Source: https://dkolf.de/dkjson-lua/documentation Use `json.quotestring` to properly escape special characters in a UTF-8 string for safe inclusion in JSON. This is useful when manually constructing JSON strings or within custom `__tojson` functions. ```lua json.quotestring (string) ``` -------------------------------- ### Decode JSON string to Lua table Source: https://dkolf.de/dkjson-lua Use `json.decode` to parse a JSON string into a Lua table. The function returns the decoded object, the position after the decoded data, and an error message if parsing fails. Requires `require("dkjson")`. ```lua local json = require ("dkjson") local str = [[ { "numbers": [ 2, 3, -20.23e+2, -4 ], "currency": "\u20AC" }]] local obj, pos, err = json.decode (str, 1, nil) if err then print ("Error:", err) else print ("currency", obj.currency) for i = 1,#obj.numbers do print (i, obj.numbers[i]) end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.