Skip to content

Instantly share code, notes, and snippets.

@ikesyo
Last active March 14, 2016 04:43
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 ikesyo/927a17b96ee289d860cc to your computer and use it in GitHub Desktop.
Save ikesyo/927a17b96ee289d860cc to your computer and use it in GitHub Desktop.
Convert a JSON string into a valid JSON object
// https://twitter.com/watura/status/708164552882425856
import Himotoki
struct Foo: Decodable {
let JSON: [String: AnyJSON]
static func decode(e: Extractor) throws -> Foo {
let dictFromJSONStringTransformer = Transformer<String, [String: AnyJSON]> { string in
guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else {
throw customError("Failed to convert a string to a data: \(string)")
}
let JSON = try NSJSONSerialization.JSONObjectWithData(data, options: [])
guard let JSONDict = JSON as? [String: AnyJSON] else {
throw typeMismatch("\([String: AnyJSON].self)", actual: JSON, keyPath: nil)
}
return JSONDict
}
return try self.init(JSON: dictFromJSONStringTransformer.apply(e <| "json_string"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment