Skip to content

Instantly share code, notes, and snippets.

@Prate-k
Last active March 3, 2019 11:36
Show Gist options
  • Save Prate-k/84524e98a924fee3dc87d854cf8c0683 to your computer and use it in GitHub Desktop.
Save Prate-k/84524e98a924fee3dc87d854cf8c0683 to your computer and use it in GitHub Desktop.
Accessing JSON values with unknown keys using recursion
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