2014-11-05 40 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