1

I am trying to get a value from json in Swift. I have added an image of the data tree. My previous attempts have not worked. Below is code which prints the full json object which is what I don't want.

json tree image enter image description here

import PlaygroundSupport
import UIKit

let url = URL(string: "https://api.data.gov.sg/v1/transport/taxi-availability")
var request = URLRequest(url: url!);
request.addValue("xxxx", forHTTPHeaderField: "api-key")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard error == nil else {
        print(error)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }

    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    //print(json)

    }//end



//["features"]??[0]?


task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true
Anantha Raju C
  • 1,780
  • 12
  • 25
  • 35
Will
  • 21
  • 1
  • 4
  • Possible duplicate of [How to print JSON values using a loop in Swift 3?](http://stackoverflow.com/questions/39485205/how-to-print-json-values-using-a-loop-in-swift-3) – Suhaib Nov 06 '16 at 06:21

3 Answers3

3

You just need to do something with the json you've been vended:

let task = URLSession ... { data, response, error in
    let json = JSONSerialization.jsonObject(...)

    if let json = json as? [String: Any] {
       // now you have a top-level json dictionary
       for key, value in json {
           print("json[\"\(key\")] = \(value)")
       }
    }
}
par
  • 17,361
  • 4
  • 65
  • 80
2

I didn't verify the following code but it should work for the son tree you provided. (disclaimer: might have some errors but its mostly correct)

if let json =  (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String:Any]
  , let features = json["features"] as? [Any]
  , let firstFeature = features[0] as? [String:Any]
  , let properties = firstFeature["properties"] as? [String:Any]            
  , let taxiCount = properties["taxi_count"] as? Int 
{
    print(taxiCount)
}
DerrickHo328
  • 4,664
  • 7
  • 29
  • 50
  • I know this is late, but, when I type in something like "features" it says Use of unresolved identifier 'features', is there a solution? @DerrickHo328 – Argiator Morimoto May 05 '19 at 13:25
1

If Json is dictionary

let json = try! JSONSerialization.jsonObject(with: data, options: [])
let jsonDict = json as? NSDictionary
//if you have a key name
let name = jsonDict["name"] as? String
//and so on
//if you have a array in your dictionary
let likes = jsonDict["likes"] as? NSArray
let numberOfLikes = likes.count
for eachLike in likes {
let likerName = eachLike["liker_name"] as? String
}