AppleScript如何从CURL返回的JSON结果中提取access_token存入新变量
解决方案
你可以任选以下两种方案实现,第一种代码更简洁,第二种无需额外安装工具:
- 方案1:使用
jq工具(轻量JSON处理工具,开发环境常用)
你只需要在原有token变量的基础上,添加如下代码即可提取值:
也可以直接把解析逻辑合并到curl请求中,一步拿到目标值,无需额外存储set tokenvalue to do shell script "echo " & quoted form of token & " | jq -r '.access_token'"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 additionsset 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
相关产品推荐
相关产品推荐

