-1

I had problem with SwiftyJSON and I don't really understand their documentation.

I did

let jsonArray = JSON(jsonData)

let json = jsonArray["Data"]   

(edit)How do i get all the the "names" by using loop(just the names not what is inside the names)? like I want to print out every set one by one.

{ "Data": { "Jenn": { "Id": "21227", "DOB": "1/1/1989" }, 
            "Kenny": { "Id": "20909", "DOB": "1/10/1989" }, 
            "Lisa": { "Id": "28223", "DOB": "11/1/1980" }, 
            "John": { "Id": "29462", "DOB": "2/7/1991" }, 
            "Emma": { "Id": "3744", "DOB": "10/7/2000" }, 
            "David": { "Id": "3748", "DOB": "4/9/1980" }, 
            "Tim": { "Id": "1182", "DOB": "5/5/1999" }, 
            "Joan": { "Id": "7605", "DOB": "6/12/1995" }, 
            "Jack": { "Id": "3808", "DOB": "3/20/1990" } 
           } 
 }

I'm sorry if it looks confusing. Thank you!!

vadian
  • 274,689
  • 30
  • 353
  • 361
14079_Z
  • 401
  • 5
  • 20
  • as I'm getting your json format is not correct. Before parsing the json data please verify the json format on http://jsonviewer.stack.hu/ if you are successfully able to format the jsondata over jsonviewer than it can easily parsed. – bestiosdeveloper Jul 27 '18 at 04:48
  • Hi, thanks for point it out. just added the missing brackets. – 14079_Z Jul 28 '18 at 05:08

3 Answers3

0

json is not a Array but a Dictionary. So you should use json["Emma"].

itsapple
  • 28
  • 5
  • Hi, thank you for answering. I think the way I ask was incorrect. After I did json = jsonArray["Data"] it just print the entire thing. And so far i can only get the first dict by json["Data"].first. How do I get the second dict in the json? what if the json contains 100+ of array of dicts? how do i get all of it by using loops? – 14079_Z Jul 28 '18 at 05:35
0

json is Dic, you can use it like this:

//using key to get sub data
let dic = json["Emma"]
//get keys array
let names = json.keys;
if let firstname = names.first{
    print(firstname)
}
selton
  • 77
  • 4
  • Hi, thank you for answering. I think the way I ask was incorrect. After I did json = jsonArray["Data"] it just print the entire thing. And so far i can only get the first dict by json["Data"].first. How do I get the second dict in the json? what if the json contains 100+ of array of dicts? how do i get all of it by using loops? I'm sorry it sounds really confusing I'm trying my best to explain what I was asking :/ – 14079_Z Jul 28 '18 at 05:32
0

First of all the root object is a dictionary, not an array, please note the braces ({}).

The names are dictionary keys in the dictionary for key Data

do {
    let jsonDictionary = try JSON(data: data)
    if let data = jsonDictionary["Data"].dictionary {
        let names = data.keys
        for name in names {
            print(name)
        }
    }
} catch {
    print(error)
}
vadian
  • 274,689
  • 30
  • 353
  • 361