1

If I have the following as a String, how can I turn it into a Dictionary in Swift 4?

{"cover_image":"CI","profile_image":"PI","github":"","location":"Somewhere between the north pole and the south pole","name":"R","website":"mysitesucksyoudon'twannavisititrightnow.imforreal","about":"Yeah, I'm a human."}

Rishi556
  • 192
  • 2
  • 11

1 Answers1

3

You can use JSONSerialisation method class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any:

let str = """
{"cover_image":"CI","profile_image":"PI","github":"","location":"Somewhere between the north pole and the south pole","name":"R","website":"mysitesucksyoudon'twannavisititrightnow.imforreal","about":"Yeah, I'm a human."}
"""
let dict = (try? JSONSerialization.jsonObject(with: Data(str.utf8))) as? [String:String] ?? [:]

print(dict)  // ["name": "R", "location": "Somewhere between the north pole and the south pole", "website": "mysitesucksyoudon\'twannavisititrightnow.imforreal", "github": "", "cover_image": "CI", "about": "Yeah, I\'m a human.", "profile_image": "PI"]
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571