util.json
Sometimes you need to deal with JSON objects. This library can serialize Lua objects to JSON and parse them back.
Example use
local json = require "util.json";
local rawdata = [[
{
"mydata": "Hello World"
}
]]
local parsed = json.decode(rawdata);
print(parsed.mydata); -- prints "Hello World";
print(json.encode({foo = "bar", baz = {1, 2, 3}}))
--> {"baz":[1,2,3],"foo":"bar"}
Reference
encode(data)
Returns a string representing the given data (usually, but not always, a table).
decode(string)
Returns the original data, given a string returned by encode(data).
Lua type mapping
Arrays
Empty Lua tables ({}
) will be encoded as JSON objects, even if they were intended to be empty JSON arrays ([]
. As a workaround, use the util.array
library for arrays, then they will always be encoded as JSON arrays, even if empty.
When decoding, JSON arrays will be assigned the util.array
metatable.
Objects
Lua tables support arbitrary types as both keys and values, while JSON objects are limited to string keys, so a table like {[true]="yes"}
can’t be represented in JSON.
util.json
employs a thing for this, it encodes such table pairs into an array in the field "__hash"
:
{[true]=1,[false]=0}
→ {"__hash":[true,1,false,0]}
A table with both string keys and an array part will have its array items encoded in a field called "__array"
:
{foo=1,bar=2,"lorem","ipsum"}
→ {"foo":1,"bar":2,"__array":["lorem","ipsum"]}