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
开发者文档
使用帮助
使用说明 脚本菜单 常见问题
脚本开发
开发指南
插件开发
快速开始 开发指南 示例插件
API 参考
概览 API 查询 插件信息 日志 Finder 上下文 插件设置 国际化
UI 与交互
对话框 进度条 系统通知 选择器 WebView 状态栏 Dock
文件与路径
文件操作 路径工具 Finder 操作 废纸篓 扩展属性 元数据 文件监听
数据格式
JSON Plist CSV XML PDF 图片
文本与编码
字符串 正则表达式 日期时间 颜色 加密编码
系统
Shell 命令 进程管理 应用管理 系统信息 AppleScript 快捷指令
系统信息
网络信息 电源/电池 屏幕/外观 音频控制 蓝牙设备 位置服务
网络
HTTP 请求 WebSocket URL 工具
输入与剪贴板
键盘模拟 鼠标模拟 全局热键 剪贴板 窗口管理
存储
SQLite Keychain UserDefaults
媒体
文字识别 二维码
工具
归档 类型标识 分享 定时器 防休眠 并发/协程