0

I'm having trouble accessing/printing some nested JSON data. The code below works when I use commented print(json) to print the entire array, but when I try to step inside the the objects it gives an error. I think it's because instead of a straight array the structure is a little different. JSON data is nested in a dictionary called "data"

Would love some help trying to print the "title" fields as an example. Thanks a lot.

func fetchTvItems()   {

    let url = NSURL(string: "hidden")

    URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in

        if error != nil {
            print(error ?? "URLSession error")
            return
        }

        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

            for dictionary in json as! [[String: AnyObject]]    {
                print(dictionary["title"]!)
            }
            //print(json)

        } catch let jsonError {
            print(jsonError)
        }

    }.resume()
4
  • the var json is your root object. You need to extract the "data" array from the root json. after you do that, this will the array you loop on. Commented Nov 9, 2017 at 12:04
  • Side note - Your API is completely exposed. You really should have it more secure. Commented Nov 9, 2017 at 12:19
  • Ah yeah we are, it's just temporary. But thanks Lirik for your help :) Commented Nov 9, 2017 at 12:29
  • Use SwiftyJSONAccelarator for JSON Serialization. Commented Nov 9, 2017 at 13:13

5 Answers 5

2

You are stating wrong things here.

First thing you are storing json data in Array. But it's inside Dictionary keyed "data"

so, first try to store dictionary to array. Try below code

if let arry = json["data"] as? [[String:AnyObject]] {
         for dictionary in arry {
                print(dictionary["title"]!)
            }  
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your code it correct but you need to cast let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? Dictionary<String, Any>
2

First of all a JSON dictionary in Swift 3+ is [String:Any] rather than [String:AnyObject].

  • The root object is a dictionary ([String:Any]).
  • The value for key data is an array of dictionaries ([[String:Any]]).

Please read the JSON. It's very easy. {} is dictionary, [] is array.

The option .mutableContainers is completely useless in Swift.

    do {
        if let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any],
           let data = json["data"] as? [[String:Any]] {

              for dictionary in data {
                  print(dictionary["title"] as? String ?? "n/a")
              }
           }
    } catch {
        print(error)
    }

Comments

1

Hope help you

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

is String data root. You must access to key "data" string json.

let array = json["data"] as? [[String:AnyObject]

Now you can use array and for data you want.

Good luck.

Comments

1

Swift 4

With JSONSerialization it can be done easily.

func convertToDictionary(text: String) -> [String: Any]? {
    if let data = text.data(using: .utf8) {
        do {
            return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
        } catch {
            // Handle Error
        }
    }
    return nil
}

Comments

0

This is testet with your code

let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]

for item in json["data"] as! [[String: AnyObject]] {
     print(item["title"] as! String)
}

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.