Skip to content

Instantly share code, notes, and snippets.

@koingdev
Created June 5, 2019 13:46
Show Gist options
  • Save koingdev/132de1e1e60b58a673e6b22ae136d161 to your computer and use it in GitHub Desktop.
Save koingdev/132de1e1e60b58a673e6b22ae136d161 to your computer and use it in GitHub Desktop.
Make nested dictionary flat again
/*
BEFORE = ["id": 1, "sergio": ["yume": ["ssk": 999]], "product": ["name": "AAA", "description": ["banana": "yellow"]]]
AFTER = ["sergio/yume/ssk": 999, "id": 1, "product/name": "AAA", "product/description/banana": "yellow"]
*/
typealias JSON = [String : Any]
let nested: JSON = ["id": 1, "product": ["name": "AAA", "description": ["banana": "yellow"]], "sergio": ["yume": ["ssk": 999]]]
extension JSON where Key: ExpressibleByStringLiteral, Value: Any {
/// Convert nested dictionary to flatten
///
/// - Returns: flat dictionary
func toFlatten() -> JSON {
var output: JSON = [:]
func flattenDic(_ dic: JSON, parentPath: String = "", output: inout JSON) {
for (key, val) in dic {
let path = parentPath.isEmpty ? key : "\(parentPath)/\(key)"
// Found dictionary ?
if let childDic = val as? JSON {
flattenDic(childDic, parentPath: path, output: &output)
} else {
output[path] = val
}
}
}
flattenDic(self, output: &output)
return output
}
}
print("BEFORE = \(nested)\n")
print("AFTER = \(nested.toFlatten())")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment