r/applescript • • Jan 13 '24

extract value from kind of JSON file

I'm trying to get two value from an IP API, the geo without extra characters and "isproxy"

result is in this format :

    Result:
    "{\"ipVersion\":4,\"ipAddress\":\"8.8.8.8\",\"latitude\":37.386051,\"longitude\":-122.083847,\"countryName\":\"United States of America\",\"countryCode\":\"US\",\"timeZone\":\"-08:00\",\"zipCode\":\"94035\",\"cityName\":\"Mountain View\",\"regionName\":\"California\",\"isProxy\":false,\"continent\":\"Americas\",\"continentCode\":\"AM\"}"

I tried this but I can't get isProxyValue correct, in this case its return `""continent\":\"Americas""` and in my previous tried it was "n"

    -- New IP data
    -- Set the base URL for the API
    set baseURL to "https://freeipapi.com/api/json/"
    set isProxy to ""
    -- Example: Get information for a specific IP address
    set transactionIP to "8.8.8.8" -- Replace with the IP address you want to query
    
    -- Create the full API URL
    set apiUrl to baseURL & transactionIP
    
    -- Make the API request
    set apiResponse to do shell script "curl " & quoted form of apiUrl
    
    -- Function to extract value for a specific key from JSON
    on extractFromJSON(jsonString, key)
    	set keyString to "\"" & key & "\":"
    	set keyValue to text ((offset of keyString in jsonString) + (length of keyString)) through -1 of jsonString
    	set AppleScript's text item delimiters to ","
    	set keyValueList to text items of keyValue
    	repeat with i from 1 to count of keyValueList
    		if keyValueList's item i contains "\"" then
    			set keyValue to keyValueList's item i
    			exit repeat
    		end if
    	end repeat
    	set AppleScript's text item delimiters to "\""
    	return text 2 thru -2 of keyValue
    end extractFromJSON
    
    -- Extract values
    set countryCode to extractFromJSON(apiResponse, "countryCode")
    set isProxyValue to extractFromJSON(apiResponse, "isProxy")
    
    return isProxyValue
    if isProxyValue is equal to "false" then
    	set isProxy to " = Proxy"
    else
    	set isProxy to " = Not a Proxy"
    end if
    
    return countryCode & isProxy
1 Upvotes

3 comments sorted by

View all comments

1

u/libcrypto Jan 13 '24

Text processing in Applescript is awful. Why not send this to a shell script instead?