I can not find how to make json readable form. Suppose there is {"x": 5, "b": 6} I would like to get

{ "x":5 }, { "b":6 } 

The keys are not known in advance

Do so

 func convertToDictionary(text: String) -> [String: Any]? { if let data = text.data(using: .utf8) { do { return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { print(error.localizedDescription) } } return nil } 

Comes:

 ["x": 5, "b": 6] 

    1 answer 1

    You must first translate the string in json

     func convertToDict(text:String) -> [String:Any]? { if let data = text.data(using: .utf8) { do{ return try JSONSerialization.jsonObject(with: data, option: []) as? [String:Any] }catch{ print(error.localizedDescription) } } return nil } 

    And only then in this type

     func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String { if JSONSerialization.isValidJSONObject(value) { do{ let data = try JSONSerialization.dataWithJSONObject(value, options: options) if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) { return string as String } }catch { print("error") } } return "" } 
    • Thanks, works - user233428