chr0x
chr0x

Reputation: 1251

Create a string containing quotes without escaping

need to send a json string that contains quotes:

"{"property1": false, "property2": "orange"}"

but when I mount that string the return I have contains \" instead of only ":

"{\"property1\": false, \"property2\": \"orange\"}"

this is a problem because I'm sending that string to be processed by a server. How can I send this string without the escape characters "\" ?

Upvotes: 1

Views: 1708

Answers (1)

vadian
vadian

Reputation: 285290

Don't worry. The backslashes are virtual, they are added to be able to display double quotes in a literal string.

These lines convert the dictionary to JSON and prints the raw data. A backslash is 0x5c, a double quote 0x22.

As you can see there is no backslash in the data.

let dict : [String:Any] = ["property1": false, "property2": "orange"]
let data = try! JSONSerialization.data(withJSONObject: dict)
print(data as NSData)
// <7b227072 6f706572 74793222 3a226f72 616e6765 222c2270 726f7065 72747931 223a6661 6c73657d>

When printing the string in a Playground you see

enter image description here

Upvotes: 3

Related Questions