Skip to content

Instantly share code, notes, and snippets.

@koromiko
Created December 29, 2020 03:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koromiko/5aac826dd7ca50547325bc7a9559388c to your computer and use it in GitHub Desktop.
Save koromiko/5aac826dd7ca50547325bc7a9559388c to your computer and use it in GitHub Desktop.
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