Skip to content

Instantly share code, notes, and snippets.

@Prate-k
Prate-k / searchJSONWithoutKeys.swift
Last active March 3, 2019 11:37
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 {
@Prate-k
Prate-k / jsonWithoutKeys.swift
Last active March 3, 2019 11:36
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
}
@Prate-k
Prate-k / jsonUsingKeys.swift
Last active March 3, 2019 11:36
Accessing JSON values with the known keys from JSON response
if let query = json["query"] as? [String:Any] {
if let pages = query["pages"] as? [String:Any] {
if let page = pages["30984"] as? [String:Any] {
if let revisions = page["revisions"] as? [[String:Any]] {
if let element = revisions[0] as? [String:Any] {
if let htmlData = element["*"] as? String {
print(htmlData)
}
}
}