I'm querying the ipstack API for data with a list of IPs using a repeat
loop and JSON Helper.
I'm looping through a list of IPs, but I can't get the Script Editor to return all the results; I only get the one cityName
of the last IP in theListOfips
in the results pane, "Tallahassee"
.
How can I get the Script Editor to show a list of all cities in the result pane, with a carriage return after each?
set theListOfips to {"104.137.108.23", "107.140.9.50", "146.201.166.248"}
tell application "JSON Helper"
repeat with theCurrentValue in theListOfips
delay 2
set json to fetch JSON from
"http://api.ipstack.com/" & theCurrentValue & "?access_key=theAPIkey&fields=city"
set cityName to city of json
end repeat
end tell
Best Answer
The immediate solution would be to use the
Replies
pane rather than theResults
pane inScript Editor
. It will print a live result from each AppleScript command executed during the run of a script, whereas theResults
pane only returns the overall result of the script's execution (which equates to the result of only the final command).The final command in your script will be
set cityName to city of json
, and so the result of your script will be the value ofcityName
after it has been set to the value from the JSON record that pertains specifically to the last IP address in your list, i.e."146.201.166.248"
.So for a more comprehensive solution, you can edit your script slightly so that the last command will be one that returns what you actually want. You can do this by first declaring a variable as an empty
list
, into which you would add anitem
of data in each iteration of your repeat loop. After the repeat loop is complete, your final command would simply be a reference to thatlist
so as to have AppleScript evaluate its contents and return the result:This returns a list of all the city names (or a list of lists of IP address-city name pairs if you elect to use the line I commented out as an alternative). To make this list into a single piece of text with one city per line, use the list that contains city names only; set the
text item delimiters
tolinefeed
; then coerce thelist
totext
. So, instead ofreturn the cityNames
, you would have: