app.json - JSON API
JSON encoding and decoding.
Methods
app.json.parse(jsonString)
Parses a JSON string into a Lua table.
Parameters:
jsonString(string) - JSON string
Returns: any|nil - Lua value or nil (on parse failure)
local data = app.json.parse('{"name": "test", "count": 123}')
-- { name = "test", count = 123 }
local arr = app.json.parse('[1, 2, 3]')
-- { 1, 2, 3 }
app.json.stringify(value, pretty?)
Converts a Lua value to a JSON string.
Parameters:
value(any) - Value to convert (table, string, number, etc.)pretty(boolean, optional) - Whether to format the output (default false)
Returns: string|nil - JSON string or nil
-- Compact format
local json = app.json.stringify({name = "test", count = 123})
-- '{"name":"test","count":123}'
-- Pretty format
local json = app.json.stringify({name = "test", count = 123}, true)
-- {
-- "count": 123,
-- "name": "test"
-- }
app.json.readFile(path)
Reads and parses JSON from a file.
Parameters:
path(string) - JSON file path
Returns: any|nil - Lua value or nil
local config = app.json.readFile("/path/to/config.json")
if config then
app.log.info("Config: " .. config.name)
end
app.json.writeFile(path, value, pretty?)
Writes a Lua value to a JSON file.
Parameters:
path(string) - File pathvalue(any) - Value to writepretty(boolean, optional) - Whether to format (default false)
Returns: boolean - Whether successful
app.json.writeFile("/path/to/output.json", {
name = "test",
items = {1, 2, 3}
}, true)
Type Mapping
| JSON Type | Lua Type |
|---|---|
| object | table (hash table) |
| array | table (array) |
| string | string |
| number | number |
| boolean | boolean |
| null | nil |
Examples
Reading a Configuration File
function MyPlugin:loadConfig()
local configPath = app.path.join(app.context.pluginDirectory(), "config.json")
if not app.path.exists(configPath) then
-- Create default configuration
self.config = {
version = "1.0.0",
settings = {
quality = 90,
format = "PNG"
}
}
app.json.writeFile(configPath, self.config, true)
else
self.config = app.json.readFile(configPath)
end
end
Processing an API Response
function MyPlugin:fetchData(url)
local response = app.http.get(url)
if not response or response.status ~= 200 then
app.log.error("Request failed")
return nil
end
local data = app.json.parse(response.body)
if not data then
app.log.error("JSON parse failed")
return nil
end
return data
end