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?

2

5 Answers 5

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)")
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is invalid now for Swift 3. It gives error: Type 'AnyObject' does not conform to protocol 'Sequence'
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.

Comments

1

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

Comments

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) 
    }
}

Comments

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)!

1 Comment

Can you have the keys in an ordered manner? The JSON is ordered.

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.