【问题标题】:How to get this applescript working?如何让这个applescript工作?
【发布时间】:2015-01-01 16:07:33
【问题描述】:

所以这个小转移的目标是能够选择一段包含 URL 的文本,并让 OS X 使用 goo.gl URL 缩短服务将其转换为短 URL。

为此,我使用 Automator 创建了一个服务,该服务接受文本输入并将该输入传递给“运行 AppleScript”操作。下面列出了 AppleScript。

我已经安装了 node.js v0.10.33 并且还安装了一个名为 json (http://trentm.com/json/) 的节点包

只要我不将输出通过管道传输到 json 节点应用程序,下面的脚本就可以正常工作。
带有管道到 json 节点应用程序的 curl 命令在终端中完美运行。

我的猜测是 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

【问题讨论】:

    标签: node.js applescript osx-yosemite automator url-shortener


    【解决方案1】:

    在 Applescript 中处理 JSON 的一个很好的工具是免费的 App JSON Helper(App Store)。它将 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
    

    你好,迈克尔/汉堡

    【讨论】:

    • 谢谢,我去看看。为了我自己的启迪,我想知道为什么我写的版本不起作用 - 但是当我有 更多 更多时间时,我可以解决这个问题 :)
    【解决方案2】:

    为什么会有“return curlCommand”?你真的不想要“返回jsonResult”吗?

    诚然,我对 json 一无所知,但 curl 命令的结果是一个字符串,我知道如何在 applescript 中解析一个字符串。这是我将如何编写将其解析为字符串的代码的方法。注意我使用这个网页的 url 作为“输入”...

    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
    

    【讨论】:

    • 为混淆表示歉意。你是对的,我确实想返回 jsonResult。我在调试过程中返回 curlCommand,但忘记改回来了。
    猜你喜欢
    • 2020-08-16
    • 2013-04-15
    • 1970-01-01
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多