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

AppleScript如何从CURL返回的JSON结果中提取access_token存入新变量

解决方案

你可以任选以下两种方案实现,第一种代码更简洁,第二种无需额外安装工具:

  • 方案1:使用jq工具(轻量JSON处理工具,开发环境常用)
    你只需要在原有token变量的基础上,添加如下代码即可提取值:
    set tokenvalue to do shell script "echo " & quoted form of token & " | jq -r '.access_token'"
    
    也可以直接把解析逻辑合并到curl请求中,一步拿到目标值,无需额外存储token变量:
    set tokenvalue to (do shell script "curl -X POST https://api.whatever.test/auth/signin --header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'username=MYUSERNAME' --data-urlencode 'password=MYPASSWORD' --data-urlencode 'grant_type=password' --data-urlencode 'client_id=myclientid' --data-urlencode 'client_secret=myclientsecret' | jq -r '.access_token'")
    
    参数-r的作用是输出原始字符串,自动移除JSON字段自带的双引号。
  • 方案2:系统原生API解析(无需安装任何额外工具)
    先在你的AppleScript文件最开头引入系统框架:
    use framework "Foundation"
    use scripting additions
    
    再添加如下提取代码即可:
    set jsonData to current application's NSData's dataWithBytes:(token's UTF8String()) length:(length of token)
    set jsonDict to current application's NSJSONSerialization's JSONObjectWithData:jsonData options:0 error:(missing value)
    set tokenvalue to (jsonDict's valueForKey:"access_token") as text
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:54:03