How to fetch the key from JSON in Swift?

橙三吉。 提交于 2021-02-18 19:35:19

问题


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?


回答1:


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



回答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.




回答3:


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




回答4:


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



回答5:


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


来源:https://stackoverflow.com/questions/36564412/how-to-fetch-the-key-from-json-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!