我有一个基于Web的API,我想通过AppleScript发送POST/GET请求.我想检索并解析响应,以便我可以将其提供给另一个应用程序.
这可能吗?如果是这样,怎么样?
例如,JSON数据将如下所示:
{"result":"success","image":,"foo", "name":"bar"}
我需要在AppleScript中解析JSON,并制作了一个非常简单的可编写脚本的后台应用程序来执行此操作.它实际上只是将两个框架(JSON,Appscript)联系在一起.
它现在可以在Mac AppStore上免费获得.您可以在我们的网站上查看更多示例.
用法很简单:
tell application "JSONHelper"
-- return JSON from an AppleScript list
set jsonString to make JSON from {"A", "B", "C"}
log jsonString
set asList to read JSON from jsonString
-- return JSON from an AppleScript record
set jsonString to make JSON from {a_string:"string", a_list:{"abc", 123, false, true}}
log jsonString
-- return an AppleScript record from JSON
set asRecord to read JSON from jsonString
log asRecord
end tell
Run Code Online (Sandbox Code Playgroud)
为了回答特定问题(快速重读后),Applescript 唯一的 Web 支持是通过库URL Access Scripting,它只是终端curl命令的包装器。它有点问题,并且没有按应有的方式报告所有内容。
除此之外,Applescript 中也没有原生 JSON 支持,这样做会有点痛苦。为了解析 JSON,您需要使用Applescript's text item delimiters.
set mJson to "\"result\":\"success\",\"image\":\"foo\", \"name\":\"bar\"" -- get your data into a string somehow, like a function
set AppleScript's text item delimiters to {","}
set keyValueList to (every text item in mJson) as list
set AppleScript's text item delimiters to ""
(*"result":"success", "image":"foo", "name":"bar"*)
repeat with thiskeyValuePair from 1 to (count keyValueList)
set theKeyValuePair to item thiskeyValuePair of keyValueList
set AppleScript's text item delimiters to {":"}
set theKeyValueBufferList to (every text item in theKeyValuePair) as list
set AppleScript's text item delimiters to ""
set theKey to item 1 of theKeyValueBufferList
(*"result"*)
set theValue to item 2 of theKeyValueBufferList
(*"success"*)
end repeat
Run Code Online (Sandbox Code Playgroud)
当一切顺利时,这一切就完成了。您必须考虑格式错误的 JSON,例如在您的示例中,其中包含不属于它的额外逗号,以及额外空格等差异。如果您可以在其他地方操作数据以获得所需的数据,我建议您这样做。Applescript 不太适合这样的事情。
| 归档时间: |
|
| 查看次数: |
9317 次 |
| 最近记录: |