能否以及如何将远程数据(例如JSON)获取到AppleScript中? [英] Can and how do you get remote data (e.g. JSON) into AppleScript?

查看:154
本文介绍了能否以及如何将远程数据(例如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唯一的网络支持就是通过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's text item delimiters.

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天全站免登陆