Search code examples
htmljsonxml-parsingxmlhttprequestapplescript

How do I read the answer of a HTML post with Apple script


How do I read certain values from this, this or this link when using applescript.
I need help with both getting the answer back from the server and with reading the JSON,XML,HTML responses (reason for multiply links)

If any one can point me to any decent documentation that would be great as well


Solution

  • Here's how you'd get the value for "city" in both the XML and JSON versions. Note that you have to convert the JSON to a PLIST in order to allow AppleScript to parse it. They're highly compatible formats, so the conversion should work flawlessly. You could parse the HTML version by treating it as XML, but that's generally a bad idea. It isn't designed to be parsed for data extraction, and would be prone to failure.

    --XML version
    
    tell application "System Events"
        set weather_XML to make XML data with properties ¬
            {id:"WeatherXML", name:"WeatherXML", text:(do shell script "curl 'http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml&appid=2de143494c0b295cca9337e1e96b00e0'")}
        get value of XML attribute "name" of XML element "city" of XML element "current" of weather_XML
        quit
    end tell
    
    --JSON version. Note the "plutil" conversion.
    
    tell application "System Events"
        set weather_PLIST to make property list item with properties ¬
            {name:"WeatherPLIST", text:(do shell script "curl 'http://api.openweathermap.org/data/2.5/weather?q=London&mode=json&appid=2de143494c0b295cca9337e1e96b00e0'|plutil -convert xml1 - -o -")}
        get value of property list item "name" of weather_PLIST
        quit
    end tell
    

    You can read more about this in the System Events dictionary, which can be accessed by typing +shift+o in Script Editor, and selecting "System Events.app" from the list.