app.json - JSON 操作 API
JSON 编码和解码。
方法
app.json.parse(jsonString)
解析 JSON 字符串为 Lua 表。
参数:
jsonString(string) - JSON 字符串
返回值: any|nil - Lua 值或 nil(解析失败)
local data = app.json.parse('{"name": "测试", "count": 123}')
-- { name = "测试", count = 123 }
local arr = app.json.parse('[1, 2, 3]')
-- { 1, 2, 3 }
app.json.stringify(value, pretty?)
将 Lua 值转换为 JSON 字符串。
参数:
value(any) - 要转换的值(表、字符串、数字等)pretty(boolean, 可选) - 是否格式化输出(默认 false)
返回值: string|nil - JSON 字符串或 nil
-- 紧凑格式
local json = app.json.stringify({name = "测试", count = 123})
-- '{"name":"测试","count":123}'
-- 格式化输出
local json = app.json.stringify({name = "测试", count = 123}, true)
-- {
-- "count": 123,
-- "name": "测试"
-- }
app.json.readFile(path)
从文件读取并解析 JSON。
参数:
path(string) - JSON 文件路径
返回值: any|nil - Lua 值或 nil
local config = app.json.readFile("/path/to/config.json")
if config then
app.log.info("配置: " .. config.name)
end
app.json.writeFile(path, value, pretty?)
将 Lua 值写入 JSON 文件。
参数:
path(string) - 文件路径value(any) - 要写入的值pretty(boolean, 可选) - 是否格式化(默认 false)
返回值: boolean - 是否成功
app.json.writeFile("/path/to/output.json", {
name = "测试",
items = {1, 2, 3}
}, true)
类型映射
| JSON 类型 | Lua 类型 |
|---|---|
| object | table(哈希表) |
| array | table(数组) |
| string | string |
| number | number |
| boolean | boolean |
| null | nil |
示例
读取配置文件
function MyPlugin:loadConfig()
local configPath = app.path.join(app.context.pluginDirectory(), "config.json")
if not app.path.exists(configPath) then
-- 创建默认配置
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
处理 API 响应
function MyPlugin:fetchData(url)
local response = app.http.get(url)
if not response or response.status ~= 200 then
app.log.error("请求失败")
return nil
end
local data = app.json.parse(response.body)
if not data then
app.log.error("JSON 解析失败")
return nil
end
return data
end