Search code examples
jsonswiftswift3nsarraynsdictionary

Parse JSON with no title Swift 3


I am pulling down a json stream? From a phant server I can pull the data down parse it and print it in xcode. I need to pull out specific values but the json does not have a title and I can not seem to figure it out.

My JSON Data

(
    {
    lat = "36.123450";
    long = "-97.123459";
    timestamp = "2017-04-26T05:55:15.106Z";
},

My Current Code in Swift

    let url = URL(string: "https://data.sparkfun.com/output/5JDdvbVgx6urREAVgKOM.json")

let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
    if error != nil {
        print("error")
    } else {
        if let content = data {
            do {
                // JSONArray 
                let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
                print(myJson)
                let Coordinates = myJson["lat"] as! [[String:Any]]
                print(Coordinates)


            } catch {
        }
    }
    }
}
    task.resume()

}

Solution

  • Please read the JSON. [] represents an array, {} a dictionary.

    The JSON is an array of dictionaries. All keys and values are String.

    let url = URL(string: "https://data.sparkfun.com/output/5JDdvbVgx6urREAVgKOM.json")
    let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
        if error != nil {
            print("error: ", error!)
        } else {
            do {
                let coordinateArray = try JSONSerialization.jsonObject(with: data!) as! [[String:String]]
                for coodinate in coordinateArray {
                    let lat = coodinate["lat"] ?? "n/a"
                    let long = coodinate["long"] ?? "n/a"
                    let timestamp = coodinate["timestamp"] ?? "n/a"
                    print("latitude: \(lat), longitude: \(long), timestamp: \(timestamp)")
                }
    
            } catch {
                print (error)
            }
        }
    }
    task.resume()
    

    As always, .mutableContainers has no effect in Swift but the tutorials which suggests that will never die off.