Skip to content

Instantly share code, notes, and snippets.

@asaday
Created March 23, 2018 02:17
Show Gist options
  • Save asaday/fd7f20633631d1d9ddc9e79e39fae4e6 to your computer and use it in GitHub Desktop.
Save asaday/fd7f20633631d1d9ddc9e79e39fae4e6 to your computer and use it in GitHub Desktop.
extension Dictionary {
init(json: String) {
self = [:]
guard let a = (try? JSONSerialization.jsonObject(with: json.dataValue, options: [])) as? Dictionary else { return }
self = a
}
func json() -> String {
guard let d = try? JSONSerialization.data(withJSONObject: self, options: []) else { return "{}" }
return String(data: d)
}
@discardableResult mutating func loadJSON(path: String) -> Bool {
guard let d = try? Data(contentsOf: URL(fileURLWithPath: path)),
let a = (try? JSONSerialization.jsonObject(with: d, options: [])) as? Dictionary else { return false }
self = a
return true
}
@discardableResult func saveJSON(path: String) -> Bool {
guard let d = try? JSONSerialization.data(withJSONObject: self, options: []),
let _ = try? d.write(to: URL(fileURLWithPath: path)) else { return false }
return true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment