0

I am using SwiftlyJSON to parse JSON. My JSON looks like this

{
“data”:[{
“id”:123,
“locations”:[{
    “lat”:345,
    “long”:678
},{
    “lat”:345,
    “long”:678
}],
”live”:yes
},{
“id”:123,
“locations”:[{
    “lat”:999,
    “long”:324
},{
    “lat”:865,
    “long”:765
}],
”live”:no
}],
“success”:true,
“status”: 200
}

I want to get every "lat" and "long" from "locations", pair them and show them in a table cell.

My code in Network Service looks like this

private func updateSearchResults(_ data: Data) {
    do {
        let json = try JSON(data: data) //successfully parsed data 
        let locations =  json["data"].arrayValue.map {$0["loactions"].arrayObject}

        print(locations) //locations array is printing out correctly
        for latlang in locations{
          if let lat = latlang["lat"]{
              print(lat) //ERROR here 
          }
        }

    } catch {
        print(error)
    }
}

Error description: Cannot subscript a value of type '[Any]' with an index of type 'String'

Now, I know the error that I can't access locations array by giving string in index but I don't know how to access the "lat" and "long" from JSON. Any help would be greatly appreciated

3
  • This line looks like a typo if let lat = latlang["late"]{ shouldn't it be "lat", dropping the e? Commented Sep 9, 2019 at 3:47
  • What's the error that you get anyway? Commented Sep 9, 2019 at 3:47
  • Yes it was a typo. Corrected the question and added the error description Commented Sep 9, 2019 at 3:50

1 Answer 1

3

You need to create an array of locations(i.e, Dictionary) using flatMap. Then, access the values as,

if let locations =  json["data"].arrayValue.flatMap { $0["loactions"].arrayObject } as? [[String: Any]] {
   for latlang in locations {
      print(latlang["lat"])
      print(latlang["long"])
   }
}

Suggestion: Stop using SwiftyJSON. Use Codable and generate your model and parsing code using this app.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.