'remove \n and slash \ from converted json string
With the following line i am converting a dict to json string:
let dummyCom = ["companyId" : company.getCompanyId()?.stringValue]
var error : NSError?
let jsonData = try! JSONSerialization.data(withJSONObject: dummyCom, options: JSONSerialization.WritingOptions.prettyPrinted)
var jsonString = String(data: jsonData, encoding: String.Encoding.utf8) // the data will be converted to the string
I am getting the below description: Printing description of jsonString:
▿ Optional<String>
- some : "{\n \"companyId\" : \"1\"\n}"
My question is how can i remove \n and \ from string.
I have tried this: jsonString = jsonString!.removingPercentEncoding but getting same result. Any help or suggetion would be helpfull
Solution 1:[1]
This is the result of using JSONSerialization.WritingOptions.prettyPrinted. Don't use this option if you don't want the newlines.
The backslashes you see are an artifact of the debugger output, don't worry about those.
Solution 2:[2]
While the accepted answer is an excellent workaround, it does not solve the root cause:
The "\n" etc are not cause by JSONSerialization. The escapes are created by printing an optional string:
print(jsonString)
The solution is much simpler: Do
if let jsonString = jsonString {
print(jsonString)
}
Now you can keep your options: JSONSerialization.WritingOptions.prettyPrinted and you have a nicely formatted JSON on your console.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Gereon |
| Solution 2 | Gerd Castan |
