json

Simple JSON encoding and decoding in pure Lua.

Info

Author: Jeffrey Friedl
License: CC-By-Attribution
Copyright: 2010-2013

Functions

Name Summary
decode

Decode JSON string into lua table

encode

Encode lua table into JSON string.

encode_pretty

Encode lua table into JSON string with nice whitespace for human consumption.

Functions : json

decode(text)

Decode JSON string into lua table

Parameters
Name Type Default Summary

text

string

string to be parsed

Returns
Type Summary

table or nil

text decoded into a table or nil if it could not

Usage
--prints: {what="books", count=3}
local json = require 'json'
local inspect = require 'inspect'
local jsonString = '{"what": "books", "count": 3}'
print(inspect(json:decode(jsonString)))

encode(value)

Encode lua table into JSON string.

Parameters
Name Type Default Summary

value

table

Table to be parsed.

Returns
Type Summary

string

value as a JSON-encoded string

Usage
--prints: '{"name":"jeff", "occupation":"Biological Computer Interface"}'
local inspect = require 'inspect'
local json = require 'json'
local someTable = {name="Jeff", occupation="Biological Computer Interface"}
print(json:encode(someTable))

encode_pretty(value)

Encode lua table into JSON string with nice whitespace for human consumption.

Parameters
Name Type Default Summary

value

table

Table to be parsed

Returns
Type Summary

string

value as a JSON-encoded string with whitespace

Usage
--prints:
-- {
--    "name": "jeff",
--    "occupation": "Biological Computer Interface"
-- }
local json = require 'json'
local someTable = {name="Jeff", occupation="Biological Computer Interface"}
print(json:encode_pretty(someTable))