2011-01-05 15 views
6

我有一個基於Web的API,我想通過AppleScript發送POST/GET請求。我想檢索並解析響應,以便將它反饋到其他應用程序。可以以及如何將遠程數據(例如JSON)轉換爲AppleScript?

這可能嗎?如果是這樣,怎麼樣?

的JSON數據將,例如,像這樣:

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

+1

我不認爲有AppleScript的這個任何原生支持(雖然我可能是錯的),但你總是可以使用'做外殼script'。 – 2011-01-05 06:18:06

回答

3

要回答的具體問題(快速重讀之後),唯一網絡支持AppleScript的已經是經過URL Access Scripting庫,只是終端的curl命令的封裝。這是有點bug,並不會報告所有事情,因爲它應該。

除此之外,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 

這一切都是在一切正常時完成的。您必須考慮格式嚴重的JSON,就像您的示例中包含不屬於它的額外逗號,以及像額外空格之類的差異一樣。如果您可以在其他地方操作數據以獲得您所需的數據,我會建議您這麼做。 Applescript對於這樣的事情並不是很好。

0

我使用正則表達式解析XML/HTML/JSON等。 AppleScript沒有對正則表達式的本地支持,但是您可以下載一個名爲Satimage的腳本添加程序,這將允許您在Applescript中使用它們。

下載並安裝腳本添加,然後查看Satimage user guide獲取說明和示例代碼。

如果您對正則表達式不熟悉(或者即使您的應用程序不熟悉),名爲RegExhibit的應用程序將幫助您爲腳本找到正確的語法。

8

我需要解析AppleScript中的JSON,並製作了一個非常簡單的可編寫腳本的後臺應用程序來執行此操作。它實際上只是將兩個框架(JSON,Appscript)聯繫在一起。

它現在在Mac AppStore上免費提供。您可以在我們的website上查看更多示例。

用法很簡單:

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 
+0

很好地完成。這加上某種HTTP請求來獲取JSON可能已經解決了我的問題。 – buley 2011-02-02 23:34:37

+0

很酷 - 我剛剛使用「do shell腳本」和curl來獲取JSON,但可能會有更優雅的東西。 – davidb 2011-02-11 13:51:07

+1

MAS版本現在具有「獲取JSON」命令以避免不得不捲曲來下載JSON。 – davidb 2014-02-09 16:52:57

1

我需要它並不需要任何新的依賴(如安裝的應用程序)的一個版本。所以我做了一個只有json編碼器/解碼器的applescript。

https://github.com/KAYLukas/applescript-json

+0

在檢查你的代碼時(我希望使用它),它看起來像你使用python而不是applescript? – simonthumper 2014-11-21 19:34:04

+0

是的,那是對的。但是python始終可以在Mac OS X上使用。我認爲只使用applescript是緩慢的方式。 – user23127 2014-11-24 16:28:07

+0

是的,它運行良好,並解碼了JSON我也想要它...只要我把它放在一個Xcode運行腳本中,儘管它給了我一些python錯誤,但我猜Xcode對它可以或不可以做的事情很有趣運行:)結束了在蘋果腳本中編寫我自己的解析器,但正如你所說,它非常緩慢! – simonthumper 2014-11-24 19:35:40

相關問題