2014-11-05 42 views
0

所以這個小改道的目標是能夠選擇一段包含URL的文本,並使用goo.gl URL縮短器服務讓OS X將其轉換爲短URL。如何讓這個applescript工作?

爲此,我使用Automator創建了一個服務,該服務接受文本輸入並將該輸入傳遞給「運行AppleScript」操作。下面列出了AppleScript。

我已經安裝的node.js v0.10.33也安裝了一個節點包叫做JSON(http://trentm.com/json/

下面的腳本工作得很好,只要我不用管輸出到JSON節點的應用程序。
捲曲命令與管道到json節點應用程序在終端工作完美。

我的猜測是與shell環境關閉,但我不知道如何看待這一點。 有什麼幫助嗎?

-- shorten URLs via goo.gl URL shortener 
-- syntax derrived from Scott Lowe @ blog.scottlowe.org 

on run {input, parameters} 

    set curlCommand to "curl https://www.googleapis.com/urlshortener/v1/url -H 'Content-Type: application/json' -d '{\"longUrl\": \"" & input & "\"}' | /usr/local/bin/json id" 

    set jsonResult to (do shell script curlCommand) 

    return jsonResult 
end run 

回答

1

在AppleScript的處理JSON一個偉大的工具是免費的應用程序JSON助手(應用程序商店)。它將JSON轉換爲Applescript字典。所以,我的回答很(非常)相似@ regulus6633職位,但沒有文字解析JSON:

set input to "http://stackoverflow.com/questions/26757656/how-to-get-this-applescript-working" 

-- Note: without piping to grep at the end! 
set curlCommand to "curl https://www.googleapis.com/urlshortener/v1/url -H 'Content-Type: application/json' -d '{\"longUrl\": \"" & input & "\"}'" 

-- getting the full JSON answer 
set jsonResult to do shell script curlCommand 

-- using JSON Helper to translate JSON to Applescript dictionary 
tell application "JSON Helper" 
    set shortURL to |id| of (read JSON from jsonResult) 
end tell 

return shortURL 

問候,邁克爾/漢堡

+0

謝謝,我會檢查一下。對於我自己的薰陶,我想知道爲什麼我寫的版本不起作用 - 但是當我有*更多的時間時,我可以用它來破解它:) – 2014-11-09 23:15:58

+0

這個作品非常完美。謝謝! – 2014-11-09 23:20:27

1

爲什麼你有「返回curlCommand」?你不是真的想要「返回jsonResult」嗎?

不可否認,我對json一無所知,但curl命令的結果是一個字符串,我知道如何解析applescript中的字符串。以下是我將如何將你的代碼解析爲一個字符串。請注意我用這個網頁的網址爲「輸入」 ...

set input to "http://stackoverflow.com/questions/26757656/how-to-get-this-applescript-working" 

set curlCommand to "curl https://www.googleapis.com/urlshortener/v1/url -H 'Content-Type: application/json' -d '{\"longUrl\": \"" & input & "\"}' | grep '\"id\"'" 
set jsonResult to do shell script curlCommand 
set shortURL to text 9 thru -2 of jsonResult 
return shortURL 
+0

appologies的混亂。你是對的,我確實想返回jsonResult。作爲我的調試過程的一部分,我正在返回curlCommand並忘記將其更改回來。 – 2014-11-09 23:13:19