Last active
March 3, 2019 11:37
-
-
Save Prate-k/b8169b486f9a76549697390e3f0940de to your computer and use it in GitHub Desktop.
searching for all values of interest within the JSON response
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 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