Skip to main content

coloX cjson JSON Module Lua Programming Guide

cjson is a high-performance JSON encoding/decoding module (implemented in C), converting between Lua values and JSON used in HTTP APIs, WebSocket messages, configuration data, and more.

Enabling the Module​

The host preloads the module; use require to access it, without usemod:

local json = require("cjson")          -- Standard version (raises a Lua error on failure)
local json = require("cjson_safe") -- Safe version (returns nil, err on failure)

Contents​

  1. Core concept: type mapping
  2. API reference
  3. Configuration
  4. cjson_safe
  5. Complete examples
  6. Complete API index

1. Core Concept: Type Mapping​

Lua → JSON(encode)​

Lua valueJSON result
table (consecutive integer keys 1..n)Array [...]
table (other/mixed key types)Object {...} (keys output after tostring conversion)
Empty table {}Object {} (not array [])
stringString (escapes ", \, control characters, etc.)
numberNumber (integers output directly; floats follow the precision setting, see §3)
booleantrue / false
json.null (sentinel, see §2)null
NaN / InfinityError by default (configurable, see §3)
function / userdata / threadError

JSON → Lua(decode)​

JSON valueLua result
objecttable (string keys)
arraytable (1-based array)
stringstring (UTF-8 preserved)
numbernumber (integer-style values are decoded as integers where possible; floats are limited by the platform's 32-bit float precision, approximately 7 significant digits)
true / falseboolean
nulljson.null sentinel (lightuserdata, because Lua nil cannot be stored in a table)

For duplicate object keys, later values overwrite earlier ones. Deep nesting is limited by decode_max_depth (default 1000 levels).

Platform numbers are 32-bit (int32 integers, float32 floats): very large integers (outside ±2^31) and high-precision decimals lose precision. Use strings when exact transmission is required.


2. API Reference​

json.encode(obj) → string​

Encodes a Lua value as a JSON string. Raises a Lua error for invalid types, excessive depth, NaN/Infinity, etc.

local json = require("cjson")
json.encode({ name = "coloX", tags = {"game", "demo"}, score = 99.5 })
-- → '{"name":"coloX","tags":["game","demo"],"score":99.5}'

json.decode(str) → value​

Parses a JSON string into a Lua value. Raises a Lua error on failure (for a non-throwing version, see §4).

local obj = json.decode('{"user":{"name":"Ming","age":18},"active":true}')
print(obj.user.name) -- Ming
print(obj.active) -- true

json.null — null Sentinel​

json.null is a lightuserdata sentinel representing JSON null in Lua (distinct from an absent field):

local obj = json.decode('{"a":null}')
print(obj.a) -- userdata: 0x0 (json.null, not nil)
print(obj.a == json.null) -- true
print(obj.b) -- nil (field absent)

-- Encode null again
obj.a = json.null
json.encode(obj) -- '{"a":null}'

Distinguishing "null value" from "missing field":

if obj.a == nil then        -- Field absent
elseif obj.a == json.null then -- Value is null
end

json.new() → module​

Creates a new module instance with independent configuration. Calling the configuration functions in §3 on it does not affect the global require("cjson") configuration.

local myjson = json.new()
myjson.encode_max_depth(20) -- Affects only myjson

3. Configuration​

All configuration functions have three-state behavior: no arguments = query (returns current value); with arguments = set (returns previous value).

FunctionDefaultDescription
encode_sparse_array(convert [, ratio [, safe]])0, 2, 10Sparse arrays: with convert=0 (default), holes follow the ratio/safe policy (small holes become null; excessive sparsity becomes an object); convert=1 always encodes sparse tables as objects
encode_max_depth(depth)1000Maximum encoding nesting depth; error if exceeded
decode_max_depth(depth)1000Maximum decoding nesting depth; error if exceeded
encode_number_precision(precision)14Significant digits for float encoding, 1-14 (platform floats are 32-bit; settings above 7 offer no practical benefit)
encode_keep_buffer(enabled)trueReuse the internal encoding buffer (disable to save memory)
encode_invalid_numbers(mode)"off"NaN/Infinity encoding: "off" errors / "on" outputs NaN and Infinity literals / "null" outputs null
decode_invalid_numbers(enabled)trueAccept NaN/Infinity literals (non-strict JSON)
local json = require("cjson")
json.decode_max_depth(64) -- Limit depth to reject malicious JSON
json.encode_invalid_numbers("null") -- NaN → null
local old = json.encode_max_depth() -- Query the current value

4. cjson_safe​

The cjson_safe API is identical to cjson, except that encode/decode return nil, err on failure instead of throwing. Suitable for external input (network responses, etc.) when you do not want to use pcall:

local json = require("cjson_safe")
local obj, err = json.decode('{"broken": ...')
if not obj then
printh("JSON parse failed: " .. tostring(err))
end

5. Complete Examples​

Parsing a JSON Response from an HTTP API​

Used with the net module (see net.md):

usemod('net')
#include colox_net.lua
#include colox_http.lua

local json = require("cjson_safe")

copas.addthread(function()
local body, code = nethttp.request("https://api.example.com/v1/data")
if not body or code ~= 200 then
printh("request failed")
return
end
local data, err = json.decode(body)
if not data then
printh("bad json: " .. tostring(err))
return
end
for _, item in ipairs(data.list or {}) do
printh(item.id .. ": " .. tostring(item.name))
end
end)

function _draw() copas.step() end

Building a Mixed Binary Protocol and JSON Text Frame with string.pack​

(string.pack is described under standard libraries in lua.md)

local json = require("cjson")
-- Frame format: 2-byte length + JSON text
local payload = json.encode({ cmd = "move", x = 12, y = 34 })
local frame = string.pack("<I2", #payload) .. payload

-- Unpack the frame
local len = string.unpack("<I2", frame)
local msg = json.decode(string.sub(frame, 3, 2 + len))

6. Complete API Index​

Function/fieldReturnsDescription
require("cjson")moduleStandard module (throws on errors)
require("cjson_safe")moduleSafe module (returns nil, err on errors)
json.encode(obj)stringEncode
json.decode(str)valueDecode
json.nulllightuserdatanull sentinel (for equality checks)
json.new()moduleNew independently configured instance
json.encode_sparse_array(...)Previous/current valueSparse array policy
json.encode_max_depth([n])Previous/current valueEncoding depth limit (default 1000)
json.decode_max_depth([n])Previous/current valueDecoding depth limit (default 1000)
json.encode_number_precision([n])Previous/current valueFloat significant digits (1-14)
json.encode_keep_buffer([b])Previous/current valueEncoding buffer reuse (default true)
json.encode_invalid_numbers([m])Previous/current valueNaN/Inf policy ("off"/"on"/"null")
json.decode_invalid_numbers([b])Previous/current valueAccept NaN/Inf literals (default true)
json._NAME / json._VERSIONstringModule name/version