I have a JSON response in the following format:
{
"coordinates": [
"-0.88676",
"51.47533"
],
[
"-0.88646",
"51.47549"
]
}
I am struggling to parse this data and append each coordinates value into an array.
I can see that this is a dictionary array but if I try to parse as a dictionary I get an error. Parsing as an array returns just the one item which essentially is the json as a single entry.
I am not adding any of my code as I believe this would be fruitless, because I have been unable to achieve what I need without errors, and have tried numerous options, all without success.
>Solution :
At the moment your JSON is not valid JSON data. But that might be a typo.
If we change this into valid JSON…
{
"coordinates": [
[
"-0.88676",
"51.47533"
],
[
"-0.88646",
"51.47549"
]
]
}
Then you could represent this as a struct like…
struct Response: Decodable {
let coordinates: [[String]] // <- this is a 2D array of coordinate pairs.
var locations: [CLLocation2D] {
coordinates
.map { $0.compactMap(Double.init) }
.filter { $0.count < 2 }
.map { ($0[0], $0[1]) }
.map(CLLocation2D.init(latitude:longitude:))
} // Something like that anyway
}
Then you can decode it like…
let data = // get the data from the network or a file etc...
let response = JSONDecoder().decode(Response.self, from: data)
That should give you the struct you want.