0

I have a local JSON file like follows.How to extract all the value of coordinates and store in arrays?Thank you!

{   
 "type":"FeatureCollection",
 "features":[
    {
    "type":"Feature",
    "geometry":{
     "type":"Point",
     "coordinates":[144.3429008,-38.17437148]
    },
   "properties":{
    "name":"Wilson Road"
   },
  {
   "type":"Feature",
   "geometry":
    {"type":"Point",
    "coordinates":[145.1801783,-37.6602503]
    },"
    properties":{
    "name":"Wilson Road"
   }
  .......

I have tried

 let path = Bundle.main.path(forResource: "json", ofType: "json")
 let jsonData=NSData(contentsOfFile: path!)
    do {
        let parsedData = try JSONSerialization.jsonObject(with: jsonData! as Data, options:[]) as! [String:AnyObject]
        let features = parsedData["features"] as! NSArray
        print(features)
    }catch{}

The output is

 ( ......
    {
    geometry =         {
        coordinates =             (
            "144.3429008",
            "-38.17437148"
        );
        type = Point;
    };
    ......

What is the next step?

1
  • What happens- does it crash? Or does the array just print nil? Commented Jan 21, 2018 at 2:09

3 Answers 3

2

Since you are using Swift 4, take advantage of Decodable. The advantage of this approach is that it is strongly-typed. Dealing with dynamic dictionaries and arrays can become confusing quickly.

The data structure below is simplified to contain only what you need in the question. Add more properties if you need them:

struct ServerResponse: Decodable {
    var type: String
    var features: [Feature]
}

struct Feature: Decodable {
    var geometry: Geometry
}

struct Geometry: Decodable {
    var coordinates: [CGFloat]
}

Usage:

let json = """
{
    "type": "FeatureCollection",
    "features": [
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [144.3429008, -38.17437148]
            },
            "properties": {
                "name": "Wilson Road"
            }
        },
        {
            "type": "Feature",
            "geometry": {
                "type": "Point",
                "coordinates": [145.1801783, -37.6602503]
            },
            "properties ": {
                "name": "Wilson Road"
            }
        }
    ]
}
""".data(using: .utf8)!

var response = try JSONDecoder().decode(ServerResponse.self, from: json)
var coordinates = response.features.map { $0.geometry.coordinates }
// [[144.3429008, -38.17437148], [145.1801783, -37.6602503]]
Sign up to request clarification or add additional context in comments.

Comments

1

First of all, your JSON isn't valid a JSON. It's missing a comma right after the key-value pair.

As for your code, you shouldn't try to cast a JSON Dictionary to [String:AnyObject], it should be [String:Any]. You also shouldn't be using NSArray in Swift, use [[String:Any]] when parsing a JSON Array of dictionaries.

You also shouldn't be using NSData in Swift, when you immediately cast it to Data. Just use the same initializer of Data in the first place.

let path = Bundle.main.path(forResource: "json", ofType: "json")
do {
    let jsonData = try Data(contentsOfFile: path!)
    guard let parsedJson = try JSONSerialization.jsonObject(with: jsonData) as? [String:Any] else {return}
    guard let features = parsedJson["features"] as? [[String:Any]] else {return}
    print(features)
} catch {
    print(error)
}

The correct JSON:

let json = """
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [144.3429008, -38.17437148]
},
"properties": {
"name": "Wilson Road"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [145.1801783, -37.6602503]
},
"properties ": {
"name": "Wilson Road"
}
}
]
}
"""

Comments

-1

You can loop through your array.

Where array is the features array you want to access:

let new_array = []
for item in array:
    for coord in item[“coordinates”]:
        new_array.append(coord)

print(new_array)

This should give you an output of:

 [144.3429008, -38.17437148, 145.1801783, -37.6602503]

If you prefer to have something like this:

[[144.3429008, -38.17437148], [145.1801783, -37.6602503]]

You can append item[“coordinates”] directly:

let new_array = []
    for item in array:
        new_array.append(item[“coordinates”])

print(new_array)

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.