0

I am working on JSON parsing in Swift.

var results = [String:[AnyObject]]()

The above results is having the data as shown below,

"fruit" = ( "apple", "orange" );

Here, data is appended dynamically during runtime. All I need is to get the keys and display them in table view as header.

How to get thekey from results in swift?

kumar
  • 481
  • 3
  • 7
  • 18

5 Answers5

4

NSJSONSerialization code example...

var results = [String:[AnyObject]]() 
let jsonResult = try NSJSONSerialization.JSONObjectWithData(results, options:NSJSONReadingOptions.MutableContainers);

for (key, value) in jsonResult {
  print("key \(key) value2 \(value)")
}
user3069232
  • 8,587
  • 7
  • 46
  • 87
  • This is invalid now for Swift 3. It gives error: Type 'AnyObject' does not conform to protocol 'Sequence' – zeeshan Dec 03 '16 at 19:47
2

You can convert JSON to dictionary as mentioned in the above link proposed by Birendra. Then suppose jsonDict is your json parsed dictionary. Then you can get collection of all keys using jsonDict.keys.

krishnanunni
  • 510
  • 7
  • 16
1

You need to use NSJSONSerialization class to convert in json format (eg. to convert in dictionary) and then get all keys from it.

Mahendra
  • 8,448
  • 3
  • 33
  • 56
1

I have used,

var results = [String:Array<DataModel>]

where,

class DataModel {
    var name: String?     
}

and to fetch the keys and value,

for i in 0...(results.length-1){
    // To print the results keys
    print(results.keys[results.startIndex.advancedBy(i)])
    // To get value from that key
    let valueFromKeyCount = (results[results.keys[results.startIndex.advancedBy(i)]] as Array<DataModel>).count
    for j in 0...(valueFromKeyCount-1) {
         let dm = results[results.keys[results.startIndex.advancedBy(i)]][j] as DataModel
         print(dm.name) 
    }
}
kumar
  • 481
  • 3
  • 7
  • 18
0

Tested with Swift 4.2 to get first key or list of keys:

This "one-liner" will return the first key, or only key if there is only one.

let firstKey: String = (
    try! JSONSerialization.jsonObject(
        with: data,
        options: .mutableContainers
    ) as! [String: Any]).first!.key

This one will get a list of all the keys as and array of Strings.

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

Both of the above examples work with a JSON object as follows

let data = """
    {
        "fruit" : ["apple","orange"],
        "furnature" : ["bench","chair"]
    }
    """.data(using: .utf8)!
timeSmith
  • 553
  • 1
  • 8
  • 16