Can and how do you get remote data (e.g. JSON) into AppleScript?

前端 未结 4 1232
猫巷女王i
猫巷女王i 2021-02-04 19:44

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.

4条回答
  •  广开言路
    2021-02-04 19:51

    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.

    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
    

    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.

提交回复
热议问题