<h1>JSON Module for Lua</h1>

<h2>Introduction</h2>

This is a module written in
without any dependencies to other external libraries. It supports UTF-8.

<h2>Download</h2>

  *

<h2>Usage</h2>

<nowiki>

<p>This module writes no global values, not even the module table.
Import it using</p>

<pre><code>json = require ("dkjson")


<p>Exported functions and values:</p>

<h3><code>json.encode (object [,

<p>Create a string representing the object. <code>Object</code> can be a table,
a string, a number, a boolean, <code>nil</code>, <code>json.null</code> or any object with
a function <code>__tojson</code> 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.</p>

<p><code>state</code> is an optional table with the following fields:</p>

<ul>
<li><code>indent</code> <br>
When <code>indent</code> (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.</li>
<li><code>keyorder</code> <br>
<code>keyorder</code> 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.</li>
<li><code>level</code> <br>
This is the initial level of indentation used when <code>indent</code> is
set. For each level two spaces are added. When absent it is set
to 0.</li>
<li><code>buffer</code> <br>
<code>buffer</code> 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.</li>
<li><code>bufferlen</code> <br>
When <code>bufferlen</code> is set, it has to be the index of the last
element of
<li><code>tables</code> <br>
<code>tables</code> 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
</ul>

<p>When <code>state.buffer</code> was set, the return value will be <code>true</code> on
success. Without <code>state.buffer</code> the return value will be a string.</p>

<h3><code>json.decode (string [, position [,

<p>Decode <code>string</code> starting at <code>position</code> or at 1 if <code>position</code> was
omitted.</p>

<p><code>null</code> is an optional value to be returned for null values. The
default is <code>nil</code>, but you could set it to <code>json.null</code> or any other
value.</p>

<p>The return values are the object or <code>nil</code>, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.</p>

<p>Two metatables are created. Every array or object that is decoded gets
a metatable with the <code>__jsontype</code> field set to either <code>array</code> or
<code>object</code>. If you want to provide your own metatables use the syntax</p>

<pre><code>json.decode (string, position, null, objectmeta, arraymeta)


<p><code>__jsonorder</code> can overwrite the <code>keyorder</code> for a specific table.</p>


<p><code>__jsontype</code> can be either <code>"array"</code> or <code>"object"</code>. This is mainly useful
for tables that can be empty. (The default for empty tables is


<h3><code>&lt;metatable&gt;.__tojson (self,

<p>You can provide your own <code>__tojson</code> 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.</p>


<p>You can use this value for setting explicit <code>null</code> values.</p>


<p>Set to <code>"dkjson

<h3><code>json.quotestring

<p>Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own <code>__tojson</code> functions.</p>

<h3><code>json.addnewline

<p>When <code>state.indent</code> is set, add a newline to <code>state.buffer</code> and spaces
according to

<h3>LPeg support</h3>

<p>When the local configuration variable
<code>always_try_using_lpeg</code> is set, this module tries to load LPeg to
replace the functions <code>quotestring</code> and <code>decode</code>. The speed increase
is significant. You can get the LPeg module at
  <a
When LPeg couldn't be loaded, the pure Lua functions stay active.</p>

<p>In case you don't want this module to require LPeg on its own,
disable the option <code>always_try_using_lpeg</code> in the source file.</p>

<p>In this case you can later load LPeg support using</p>

<h4><code>json.use_lpeg

<p>Require the LPeg module and replace the functions <code>quotestring</code> and
and <code>decode</code> with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:</p>

<pre><code>json = require "dkjson".use_lpeg()


<p>Alternatively you can use <code>pcall</code> so the JSON module still works when
LPeg isn't found.</p>

<pre><code>json = require "dkjson"
pcall (json.use_lpeg)


<p>This variable is set to <code>true</code> when LPeg was loaded successfully.</p>

</nowiki>

<h2>Examples</h2>

<h3>Encoding</h3>

<pre><code><nowiki>
<span class="luakeyword">local</span> json = <span class="lualibrary">require</span> (<span class="luastring">"dkjson"</span>)

<span class="luakeyword">local</span> tbl = {
  animals = { <span class="luastring">"dog"</span>, <span class="luastring">"cat"</span>, <span class="luastring">"aardvark"</span> },
  instruments = { <span class="luastring">"violin"</span>, <span class="luastring">"trombone"</span>, <span class="luastring">"theremin"</span> },
  bugs = json.null,
  trees = <span class="luakeyword">nil</span>
}

<span class="luakeyword">local</span> str = json.encode (tbl, { indent = <span class="luakeyword">true</span> })

<span class="lualibrary">print</span> (str)


<h4>Output</h4>

<pre><code><nowiki>
{
  "bugs":null,
  "instruments":["violin","trombone","theremin"],
  "animals":["dog","cat","aardvark"]
}


<h3>Decoding</h3>

<pre><code><nowiki>
<span class="luakeyword">local</span> json = <span class="lualibrary">require</span> (<span class="luastring">"dkjson"</span>)

str = <span class="luastring">[[
{
  "numbers": [ 2, 3, -20.23e+2, -4 ],
  "currency": "\u20AC"
}
]]</span>

<span class="luakeyword">local</span> obj, pos, err = json.decode (str, 1, <span class="luakeyword">nil</span>)
<span class="luakeyword">if</span> err <span class="luakeyword">then</span>
  <span class="lualibrary">print</span> (<span class="luastring">"Error:"</span>, err)
<span class="luakeyword">else</span>
  <span class="luakeyword">for</span> k,v <span class="luakeyword">in</span> <span class="lualibrary">pairs</span>(obj) <span class="luakeyword">do</span>
    <span class="luakeyword">if</span> <span class="lualibrary">type</span> (v) == <span class="luastring">"table"</span> <span class="luakeyword">then</span>
      <span class="lualibrary">print</span> (k)
      <span class="luakeyword">for</span> k2,v2 <span class="luakeyword">in</span> <span class="lualibrary">pairs</span>(v) <span class="luakeyword">do</span>
        <span class="lualibrary">print</span> (<span class="luastring">""</span>, k2, v2)
      <span class="luakeyword">end</span>
    <span class="luakeyword">else</span>
      <span class="lualibrary">print</span> (k, v)
    <span class="luakeyword">end</span>
  <span class="luakeyword">end</span>
<span class="luakeyword">end</span>


<h4>Output</h4>

<pre><nowiki>
currency	&euro;
numbers
	1	2
	2	3
	3	-2023
	4	-4


<h2>Versions</h2>

<h3>Version 2.0</h3>

Released 2011-05-30.

  *

<h4>Changes</h4>

  *  Optional LPeg support.
  *  Invalid input data for encoding raises errors instead of returning nil
     and the error message. (Invalid data for encoding is usually a
     programming error. Raising an error removes the work of explicitly
     checking the result).
  *  The metatable field __jsontype can control whether a Lua table is
     encoded as a JSON array or object. (Mainly useful for empty tables).
  *  When decoding, two metatables are created. One is used to mark the arrays
     while the other one is used for the objects. (The metatables are
     created once for each decoding operation to make sandboxing possible.
     However, you can specify your own metatables as arguments).
  *  There are no spaces added any longer when encoding.
  *  It is possible to explicitly sort keys for encoding by providing an array with key
     names to the option "keyorder" or the metatable field __jsonorder.
  *  The values are recognised and encoded as "null" like in
     the original JavaScript implementation.

<h3>Version 1.0</h3>

Initial version, released 2010-08-28.

  *