You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Apple Automator中用JavaScript正确解析字符串为JSON?

在OSX Automator中解决JXA的JSON解析异常问题

问题根源

Automator中使用的是JXA(JavaScript for Automation),它的原生JSON处理API(JSON.parse/JSON.stringify)和浏览器、Node.js等常规JS环境存在兼容性差异,加上shell与JXA交互时可能出现的文本转义问题,就会导致解析后属性异常、数组转对象、数值变科学计数法等问题。

解决方案

1. 先验证shell输出的原始JSON是否正常

在JXA动作里先打印shell返回的原始字符串,确认没有被Automator中间环节篡改:

// 替换成你的shell请求命令
const rawJSON = doShellScript('curl -s "https://your-api-endpoint"');
console.log('原始JSON内容:', rawJSON);

如果输出中已经出现|value|这类异常内容,说明shell输出在传递到JXA前被其他工作流动作(比如文本处理、变量替换)修改了,要确保shell动作的输出直接连接到JXA动作,中间不要添加多余的文本处理步骤。

2. 用Objective-C桥接替代原生JSON解析

JXA可以直接调用OSX的Foundation框架,用更可靠的NSJSONSerialization来处理JSON,避免原生API的bug:

ObjC.import('Foundation');

// 自定义JSON解析函数
function safeParseJSON(jsonStr) {
    const data = $.NSData.dataWithBytesLength(jsonStr, jsonStr.length);
    const options = $.NSJSONReadingMutableContainers;
    const errorRef = Ref();
    const jsonObj = $.NSJSONSerialization.JSONObjectWithDataOptionsError(data, options, errorRef);
    
    if (errorRef[0]) {
        throw new Error(`解析失败: ${errorRef[0].localizedDescription.js}`);
    }
    // 转换为JXA可直接使用的JS对象
    return jsonObj.js;
}

// 自定义JSON序列化函数
function safeStringifyJSON(obj) {
    const errorRef = Ref();
    const data = $.NSJSONSerialization.dataWithJSONObjectOptionsError(obj, 0, errorRef);
    
    if (errorRef[0]) {
        throw new Error(`序列化失败: ${errorRef[0].localizedDescription.js}`);
    }
    return $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding).js;
}

// 使用示例
const rawJSON = doShellScript('curl -s "https://your-api-endpoint"');
const parsedData = safeParseJSON(rawJSON);

// 修改数据
parsedData.value = "新的value值";
parsedData.iid = parseInt(parsedData.iid, 10); // 确保数值为整数类型

// 序列化后通过shell POST
const postData = safeStringifyJSON(parsedData);
doShellScript(`curl -X POST -H "Content-Type: application/json" -d '${postData}' "https://your-post-endpoint"`);

3. 处理POST时的字符串转义

如果用doShellScript执行POST命令,要注意序列化后的JSON字符串里的单引号会导致shell语法错误,可以用字符串替换转义:

const escapedPostData = postData.replace(/'/g, "'\\''");
doShellScript(`curl -X POST -H "Content-Type: application/json" -d '${escapedPostData}' "https://your-post-endpoint"`);

总结

JXA的原生JSON工具类存在兼容性问题,改用Foundation框架的NSJSONSerialization来处理解析和序列化,同时确保shell输出的JSON字符串未被篡改,就能解决你遇到的所有异常问题。

内容的提问来源于stack exchange,提问作者Guilherme Ruiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 00:37:37