D 2011-07-08T05:46:17.952 L dkjson U dhkolf W 9962

JSON Module for Lua

Introduction

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.

Download

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

Usage

This module writes no global values, not even the module table. Import it using

json = require ("dkjson")

Exported functions and values:

json.encode (object [, state])

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:

When state.buffer was set, the return value will be true on success. Without state.buffer the return value will be a string.

json.decode (string [, position [, null]])

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.

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.

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

json.decode (string, position, null, objectmeta, arraymeta)

<metatable>.__jsonorder

__jsonorder can overwrite the keyorder for a specific table.

<metatable>.__jsontype

__jsontype can be either "array" or "object". This is mainly useful for tables that can be empty. (The default for empty tables is "array").

<metatable>.__tojson (self, state)

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.

json.null

You can use this value for setting explicit null values.

json.version

Set to "dkjson 2.0".

json.quotestring (string)

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)

When state.indent is set, add a newline to state.buffer and spaces according to state.level.

LPeg support

When the local configuration variable always_try_using_lpeg is set, this module tries to load LPeg to replace the functions quotestring and decode. The speed increase is significant. You can get the LPeg module at http://www.inf.puc-rio.br/~roberto/lpeg/. When LPeg couldn't be loaded, the pure Lua functions stay active.

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

In this case you can later load LPeg support using

json.use_lpeg ()

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

json = require "dkjson".use_lpeg()

Alternatively you can use pcall so the JSON module still works when LPeg isn't found.

json = require "dkjson"
pcall (json.use_lpeg)

json.using_lpeg

This variable is set to true when LPeg was loaded successfully.

Examples

Encoding


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)

Output


{
  "bugs":null,
  "instruments":["violin","trombone","theremin"],
  "animals":["dog","cat","aardvark"]
}

Decoding


local json = require ("dkjson")

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
  for k,v in pairs(obj) do
    if type (v) == "table" then
      print (k)
      for k2,v2 in pairs(v) do
        print ("", k2, v2)
      end
    else
      print (k, v)
    end
  end
end

Output


currency	€
numbers
	1	2
	2	3
	3	-2023
	4	-4

Versions

Version 2.0

Released 2011-05-30. * [../../raw/dkjson.lua?name=35630290e43b332a84fb3a5504765ef6db8b7c49|dkjson.lua]

Changes

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

Version 1.0

Initial version, released 2010-08-28. * [../../raw/dkjson.lua?name=718e2b58667c2ef544fed4e28fc474267e260cb1|dkjson.lua] Z 928cc327280087756cc18e9879838b17