dkjson
Artifact [cded11e73f]
Not logged in

Chisel is closing down. This repository can be found under the new URL dkolf.de/src/dkjson-lua.fsl/.

Artifact cded11e73f40819274bacb06b7fc1e7f443cb0fe:

Wiki page [dkjson] by dhkolf 2011-07-08 05:46:17.
D 2011-07-08T05:46:17.952
L dkjson
U dhkolf
W 9962
<h1>JSON Module for Lua</h1>

<h2>Introduction</h2>

This is a [http://www.json.org/|JSON] module written in [http://www.lua.org/|Lua]
without any dependencies to other external libraries. It supports UTF-8.

<h2>Download</h2>

  *  [../../raw/dkjson.lua?name=35630290e43b332a84fb3a5504765ef6db8b7c49|dkjson.lua]

<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")
</code></pre>

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

<h3><code>json.encode (object [, state])</code></h3>

<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 <code>buffer</code>.</li>
<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 <code>true</code>.</li>
</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 [, null]])</code></h3>

<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)
</code></pre>

<h3><code>&lt;metatable&gt;.__jsonorder</code></h3>

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

<h3><code>&lt;metatable&gt;.__jsontype</code></h3>

<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
<code>"array"</code>).</p>

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

<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>

<h3><code>json.null</code></h3>

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

<h3><code>json.version</code></h3>

<p>Set to <code>"dkjson 2.0"</code>.</p>

<h3><code>json.quotestring (string)</code></h3>

<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 (state)</code></h3>

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

<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 href="http://www.inf.puc-rio.br/~roberto/lpeg/">http://www.inf.puc-rio.br/~roberto/lpeg/</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 ()</code></h4>

<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()
</code></pre>

<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)
</code></pre>

<h4><code>json.using_lpeg</code></h4>

<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)
</nowiki></code></pre>

<h4>Output</h4>

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

<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>
</nowiki></code></pre>


<h4>Output</h4>

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

<h2>Versions</h2>

<h3>Version 2.0</h3>

Released 2011-05-30.

  *  [../../raw/dkjson.lua?name=35630290e43b332a84fb3a5504765ef6db8b7c49|dkjson.lua]

<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 NaN/+Inf/-Inf are recognised and encoded as "null" like in
     the original JavaScript implementation.

<h3>Version 1.0</h3>

Initial version, released 2010-08-28.

  *  [../../raw/dkjson.lua?name=718e2b58667c2ef544fed4e28fc474267e260cb1|dkjson.lua]

Z 928cc327280087756cc18e9879838b17