您可以以及如何将远程数据(例如 JSON)导入 AppleScript? [英] Can and how do you get remote data (e.g. JSON) into AppleScript?

查看:18
本文介绍了您可以以及如何将远程数据(例如 JSON)导入 AppleScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基于 Web 的 API,我想通过 AppleScript 向其发送 POST/GET 请求.我想检索并解析响应,以便将其提供给另一个应用.

I've got a Web-based API to which I would like to send POST/GET requests via AppleScript. I'd like to retrieve and parse the response such that I can feed it into another app.

这可能吗?如果是,怎么办?

Is this possible? If so, how?

例如,JSON 数据如下所示:

The JSON data would, for example, look like this:

{"result":"success","image":,"foo", "name":"bar"}

推荐答案

要回答特定问题(快速重读后),Applescript 唯一的 Web 支持是通过 URL Access Scripting 库,这只是终端 curl 命令的包装器.它有点问题,没有按应有的方式报告所有内容.

To answer the specific question (after a quick reread), the only web support Applescript has is through the URL Access Scripting library, which is just a wrapper for the terminal's curl command. It's a bit buggy and doesn't report back everything as it should.

除此之外,Applescript 中也没有原生 JSON 支持,这样做会有点痛苦.为了解析 JSON,您需要使用 Applescript 的文本项分隔符.

Beyond that, there is no native JSON support in Applescript either, and doing so is going to be a bit painful. In order to parse the JSON, you'll need to use the 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

当一切顺利时,这一切就完成了.您必须考虑格式错误的 JSON,例如在您的示例中,它包含一个不属于它的额外逗号,以及诸如额外空格之类的差异.如果您可以在其他地方操作数据以获得所需的数据,我建议您这样做.Applescript 不太适合这样的事情.

This is all done when everything goes right. You'll have to take into consideration badly-formed JSON, as in your example which contains an extra comma where it doesn't belong, and variances like extra spaces and the like. If you can manipulate the data elsewhere to get what you need, I would suggest doing so. Applescript isn't very good for things like this.

这篇关于您可以以及如何将远程数据(例如 JSON)导入 AppleScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆