Created
December 29, 2020 03:03
-
-
Save koromiko/5aac826dd7ca50547325bc7a9559388c to your computer and use it in GitHub Desktop.
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
typealias JSON = [String: Any] | |
/// Helper for getting value from nested json dictionary | |
extension JSON { | |
/// Get the value of the given keypath. | |
/// - Parameter Path: The keypath separated by "." | |
/// - Returns: The value of the specified keypath. Return `nil` if the value is not found. | |
public subscript<T>(path path: String) -> T? { | |
get { | |
var dic: JSON? = self | |
let keyPaths = path.split(separator: ".").map { String($0) } | |
for (i, key) in keyPaths.enumerated() where dic != nil { | |
if let target = dic?[key] as? T, i == (keyPaths.count - 1) { | |
return target | |
} | |
dic = dic?[key] as? JSON | |
} | |
return nil | |
} | |
} | |
} | |
// ======= Usage ======= | |
/* | |
let jsonString = """ | |
{ | |
"nestedKey": { | |
"firstLevelKey": "firstLevelValue", | |
"secondNestedKey": { | |
"secondLevelKey": "secondLevelValue" | |
} | |
} | |
} | |
""" | |
// Object to be tested | |
let objectToTest = JSONDecoder().decode(StructToTest.self, from: data) | |
// Anser to the test | |
let jsonFact = JSONSerialization.jsonObject(with: data, options: .allowFragments) | |
// Result should be equal to the json fact | |
XCTAssertEqual(jsonFact[path: "nestedKey.secondNestedKey.secondLevelKey"], | |
objectToTest.secondLevelValue) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment