-1

I have an array of dictionaries like this one.

[["updated_at": , "expected_qty": 1, "parts_id": 1, "mappingType": service, "description": , "name": Epoxy, "created_at": , "price": 0, "win_service_id": 1, "id": 1, "mappingID": 1], ["updated_at": , "expected_qty": 1, "parts_id": 2, "mappingType": service, "description": , "name": Wood for Lami, "created_at": , "price": 0, "win_service_id": 1, "id": 2, "mappingID": 1]]

I need to make this entire array into an escaped string. Something like this.

"[{\"updated_at\":\"\",\"expected_qty\":1,\"parts_id\":1,\"mappingType\":\"service\",\"description\":\"\",\"name\":\"Epoxy\",\"created_at\":\"\",\"price\":0,\"win_service_id\":1,\"id\":1,\"mappingID\":1},{\"updated_at\":\"\",\"expected_qty\":1,\"parts_id\":2,\"mappingType\":\"service\",\"description\":\"\",\"name\":\"Wood for Lami\",\"created_at\":\"\",\"price\":0,\"win_service_id\":1,\"id\":2,\"mappingID\":1}]"

I know you can convert an array to a string using array.description but I don't know how to escape those characters within it. I searched a lot but I couldn't find a method that does this either.

I tried adding a string extension to do something like this.

extension String {
    var escaped: String {
        return self.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
    }
}

The result is this.

[[\"updated_at\": , \"expected_qty\": 1, \"parts_id\": 3, \"mappingType\": service, \"description\": , \"name\": Sill, \"created_at\": , \"price\": 0, \"win_service_id\": 8, \"id\": 3, \"mappingID\": 8]]

It looks like it's almost the expected output but notice the inner pairs of square brackets. Those must be the curly brackets.

So is there a better way to do this?

Isuru
  • 30,617
  • 60
  • 187
  • 303

1 Answers1

1

You can convert your dictionary into json using NSJSONSerialization. Try the following code out

let dict = ["key":"value","key1":"0","key2":"1"] as Dictionary<String, AnyObject>
let data = try? NSJSONSerialization.dataWithJSONObject(dict, options:NSJSONWritingOptions.PrettyPrinted)
var datastring = String(data: data!, encoding: NSUTF8StringEncoding)
Vishnu gondlekar
  • 3,896
  • 21
  • 35