Last active
March 3, 2019 11:36
-
-
Save Prate-k/84524e98a924fee3dc87d854cf8c0683 to your computer and use it in GitHub Desktop.
Accessing JSON values with unknown keys using recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func printJSON(json: [String:Any]) { | |
let jsonKeys = json.keys //Gets the list of keys on the outer-most layer of the JSON | |
for i in 0..<jsonKeys.count { | |
let level1 = json[jsonKeys.index(jsonKeys.startIndex, offsetBy: i)] //retrieves the object with the specific keys | |
if let level2 = json[level1.key] as? [String:Any]{ //if the key is another object | |
printJSON(json: level2) //send it as a new json object to the function again | |
} else if let level2 = json[level1.key] as? [[String:Any]] { //if the key is an array of objects | |
for i in 0..<level2.count { //loop through the array | |
printJSON(json: level2[i]) //send each array element to the function | |
} | |
} else if let value = json[level1.key] as? String { //if value of String/Integer/Bool type | |
print(value) //then only print values of the specified type (String-type in this case) | |
} | |
} | |
} | |
//usage: printJSON(json: json) //json is the json object deserialized from. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment