0

I am learning Swift, and I am encountering an issue parsing a JSON file from a URL file.

I'm trying to call the posts dictionary and parse the audio values from it.

let url = URL(string: "https://api.myjson.com/bins/91nzd")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
    guard let data = data, error == nil else { return }

    do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
        let posts = json["posts"] as? [String: Any] ?? [:]
        print(posts)
        let audios = posts["audio"] as? [String: Any] ?? [:]
        print(audios)
    } catch let error as NSError {
        print(error)
    }
}).resume()

This returns :, : which I believe is a nil expression. The JSON file it is calling looks like this:

{
  "posts": [
    {
      "id": "1",
      "title": "title 1",
      "audio": "https://rss-example.com/episodes/871ae23d.mp3"
    },
    {
      "id": "2",
      "title": "title 2",
      "audio": "https://rss-example.com/episodes/352ae29d.mp3"
    } 
  ] 
} 

This looks right to me from the tutorials I have read, but do you see an error? Or am I misinterpreting?

Arasuvel
  • 2,971
  • 1
  • 25
  • 40
darkginger
  • 652
  • 1
  • 10
  • 38
  • 4
    Not again :) – The value of "posts" is an *array* (`[...]`), not a dictionary. – Martin R Jan 23 '18 at 08:03
  • 1
    The reason why you get [:] is that you try to parse the array as dict and if that fails you return a [:] which this line of code here: json["posts"] as? [String: Any] ?? [:] – Kingalione Jan 23 '18 at 08:05
  • 1
    Have a look at https://stackoverflow.com/questions/39423367/correctly-parsing-json-in-swift-3 and https://developer.apple.com/swift/blog/?id=37. – Martin R Jan 23 '18 at 08:08

1 Answers1

1

Mistake is posts are Array type, try this:

    let url = URL(string: "https://api.myjson.com/bins/91nzd")
    URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
        guard let data = data, error == nil else { return }

        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
            if let posts = json["posts"] as? Array {
                for (index, element) in posts.enumerate() {
                    let audios = element["audio"] as? [String: Any] ?? [:]     
                     print(audios)
                }
            } 
        } catch let error as NSError {
            print(error)
        }
    }).resume()
Özgür Ersil
  • 6,909
  • 3
  • 19
  • 29
  • This looks good. I'm getting a last error for `Ambiguous reference to member 'subscript'` -- will update here when I figure it out. – darkginger Jan 23 '18 at 08:07