Home

Awesome

json.lua

test

A pure-Lua JSON library.

Features

Usage

local json = require "json"
json.encode { a = {1, { b = 2 } } } -- Returns '{"a":[1,{"b":2}]}'
json.decode '{"a":[1,{"b":2}]}'     -- Returns { a = {1, { b = 2 } } }
assert(json.decode "null" == json.null)
assert(not json.isObject(json.decode "{}"))
assert(json.isObject(json.decode "[]"))
assert(json.encode {1,2,[4] = 4} == "[1,2,null,4]")
json.supportSparseArray = false
local ok, err = pcall(json.encode, {1,2,[4] = 4})
assert(ok == false)
assert(err:match "invalid table: sparse array is not supported")

Optional advanced features

local json = require "json"
require "json-beautify"
local JSON = {
    name = "json",
    type = "lua"
}
print(json.beautify(JSON))
print(json.beautify(JSON, {
    newline = "\n",
    indent = "\t\t",
    depth = 0,
}))
local json = require "json"
require "jsonc"
local JSON = [[
{
    /*
     * comment
     */
    "name": "json", // comment
    "type": "lua",
}]]
local r = json.decode_jsonc(JSON)
print(r.name, r.type)
local json = require "json"
require "json-edit"
local JSON = [[
{
    /*
     * comment
     */
    "name": "json", // comment
    "type": "lua",
}]]

-- http://jsonpatch.com/
local patch = {
    op = "replace",
    path = "/name",
    value = "jsonc",
}
-- same as json.beautify
local option = {
    newline = "\n",
    indent = "    ",
}
print(json.edit(JSON, patch, option))