0
votes

I am using this JSON library to get a location from Google Geocoding the following way:

let json = JSON(url: "https://maps.googleapis.com/maps/api/geocode/json?address=94127&key=MY_API_KEY")
print(json)

It prints this:

{"results":[{"geometry":{"viewport":{"northeast":{"lat":37.7513029,"lng":-122.442329},"southwest":{"lat":37.721569,"lng":-122.472671}},"bounds":{"northeast":{"lat":37.7513029,"lng":-122.442329},"southwest":{"lat":37.721569,"lng":-122.472671}},"location":{"lat":37.734646,"lng":-122.463708},"location_type":"APPROXIMATE"},"formatted_address":"San Francisco, CA 94127, USA","types":["postal_code"],"address_components":[{"types":["postal_code"],"short_name":"94127","long_name":"94127"},{"types":["locality","political"],"short_name":"SF","long_name":"San Francisco"},{"types":["administrative_area_level_2","political"],"short_name":"San Francisco County","long_name":"San Francisco County"},{"types":["administrative_area_level_1","political"],"short_name":"CA","long_name":"California"},{"types":["country","political"],"short_name":"US","long_name":"United States"}],"place_id":"ChIJK9xbjZR9j4ARBsVPOdGWHs8"}],"status":"OK"}

Once formatted, to get the location, I need to dig down to "results" -> "geometry" –> "location" –>"lat"/"lng".
When trying to print this:

print(json["results"]["geometry"]["location"]["lat"])

...I am getting the following error:

Error Domain=JSONErrorDomain Code=500 "not an object" UserInfo={NSLocalizedDescription=not an object}

What am I doing wrong?
Thanks!

2
results is an array, so there should be some indexing before geometry.Sulthan
Like how? print(json["results"][0]["geometry"]…?LinusGeffarth
I don't know that library but something like that.Sulthan
Thanks! Your suggestion and @JianpingLiu's answer fixed it.LinusGeffarth

2 Answers

1
votes

Like @Sulthan mentioned, "results" is an array of which I need to pick an index.

print(json["results"][0]["geometry"]...

@JianpingLiu hinted me to the right direction. To access the data, I need to append .data.

The final solution therefor is:

print(json["results"][0]["geometry"]["location"]["lat"].data)
1
votes

The problem is lat/lng is not Json object, they are Json data.

Try

print(json["results"]["geometry"]["location"].lat)

Updated:

@Sulthan, Thanks for the comment about the index thing.

  print(json["results"][0]["geometry"]["location"].lat)