Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 739
guru Avatar asked Jan 21 '26 14:01

guru


1 Answers

Just replace JSONSerialization.WritingOptions.prettyPrinted with []

And you will get:

"{"companyId":1}"

And your code will look like:

let dummyCom = ["companyId" : 1]

var error : NSError?

let jsonData = try! JSONSerialization.data(withJSONObject: dummyCom, options: [])

var jsonString = String(data: jsonData, encoding: String.Encoding.utf8)
like image 189
Dharmesh Kheni Avatar answered Jan 23 '26 03:01

Dharmesh Kheni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!