Skip to content

Instantly share code, notes, and snippets.

@Prate-k
Last active March 3, 2019 11:37
Show Gist options
  • Save Prate-k/b8169b486f9a76549697390e3f0940de to your computer and use it in GitHub Desktop.
Save Prate-k/b8169b486f9a76549697390e3f0940de to your computer and use it in GitHub Desktop.
searching for all values of interest within the JSON response
func searchJSON(json: [String:Any], searchString: String) -> [String] {
var array: [String] = []
let jsonKeys = json.keys
for i in 0..<jsonKeys.count {
let level1 = json[jsonKeys.index(jsonKeys.startIndex, offsetBy: i)]
if let level2 = json[level1.key] as? [String:Any] {
array.append(contentsOf: searchJSON(json: level2, searchString: searchString))
}
else if let level2 = json[level1.key] as? [[String:Any]] {
for i in 0..<level2.count {
array.append(contentsOf: searchJSON(json: level2[i], searchString: searchString))
}
} else if let value = json[level1.key] as? String {
if value.contains(searchString) {
array.append(value)
}
}
}
return array
}
//usage: print(searchJSON(json: json, searchString: "automobile")) //searching for value which contains the word "automobile"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment