The glu.json module
The glu.json module provides JSON encoding and decoding. It converts between JSON strings/files and Lua tables.
local json = require("glu.json")Functions
| Function | Description |
|---|---|
decode(str) |
Parse a JSON string into a Lua value |
encode(value [, indent]) |
Convert a Lua table to a JSON string |
read(filename) |
Read and parse a JSON file |
write(filename, value [, indent]) |
Write a Lua table to a JSON file |
decode
Parse a JSON string and return the corresponding Lua value.
local data = json.decode('{"name": "Alice", "scores": [95, 87, 92]}')
print(data.name) --> Alice
print(data.scores[2]) --> 87JSON types map to Lua types:
| JSON | Lua |
|---|---|
| object | table (string keys) |
| array | table (integer keys) |
| string | string |
| number | number |
| boolean | boolean |
| null | nil |
Raises a Lua error if the string is not valid JSON.
encode
Convert a Lua table to a JSON string. By default the output is compact (no whitespace):
local s = json.encode({greeting = "hello", items = {1, 2, 3}})
--> {"greeting":"hello","items":[1,2,3]}Pass true as the second argument for indented output (2 spaces):
local pretty = json.encode({greeting = "hello"}, true)
--> {
--> "greeting": "hello"
--> }Pass a string to use a custom indent:
local tabs = json.encode({a = 1}, "\t")Lua tables with consecutive integer keys (1, 2, 3, …) become JSON arrays. Tables with string keys become JSON objects. Raises a Lua error if the value cannot be serialized.
read
Read a JSON file from disk and return the parsed Lua value. This is a shorthand for reading the file and calling decode:
local config = json.read("settings.json")
print(config.version)Raises a Lua error if the file cannot be read or contains invalid JSON.
write
Write a Lua table to a JSON file. The output is always formatted with 2-space indentation for readability:
json.write("output.json", {
version = 2,
tags = {"alpha", "beta"},
})This creates output.json:
{
"tags": [
"alpha",
"beta"
],
"version": 2
}Pass a string as the third argument to use a custom indent:
json.write("output.json", data, "\t")Raises a Lua error if the file cannot be written.
Example: persistent build counter
Using glu.json together with the auxiliary file or standalone:
local json = require("glu.json")
-- Load or initialize state
local state_file = "build-state.json"
local state = { count = 0 }
local f = io.open(state_file, "r")
if f then
f:close()
state = json.read(state_file)
end
-- Update
state.count = state.count + 1
state.last_build = os.date()
-- Save
json.write(state_file, state)
print("Build #" .. state.count)For data that should be tied to the document lifecycle (and trigger reruns when changed), use the _aux table instead — see Auxiliary file.