How to convert dictionary to json string without space and new line

12,740

You are decoding the serialized JSON into an object. When an object is printed into the console, you will see the indentation, and the use of equals symbols and parentheses.

Remove the .prettyPrinted option and use the data to initialize a string with .utf8 encoding.

let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: [])
let decoded = String(data: jsonData!, encoding: .utf8)!
Share:
12,740
Pak Ho Cheung
Author by

Pak Ho Cheung

Updated on July 16, 2022

Comments

  • Pak Ho Cheung
    Pak Ho Cheung almost 2 years

    I am trying to convert a dictionary to json string without space and new line. I tried to use JSONSerialization.jsonObject but I still can see spaces and new lines. Is there any way to have a string result looks something like this

    "data": "{\"requests\":[{\"image\":{\"source\":{\"imageUri\":\"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png\"}},\"features\":[{\"type\":\"LOGO_DETECTION\",\"maxResults\":1}]}]}"
    

    My conversion

    var features = [[String: String]]()
    for detection in detections {
        features.append(["type": imageDetection[detection]!])
    }
    let content = ["content": base64Image]
    let request = ["image": content, "features": features] as [String : Any]
    let requests = ["requests": [request]]
    
    let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: .prettyPrinted)
    let decoded = try! JSONSerialization.jsonObject(with: jsonData, options: [])
    print(decoded)
    

    Result

    {
        requests =     (
                    {
                features =             (
                                    {
                        type = "LABEL_DETECTION";
                    },
                                    {
                        type = "WEB_DETECTION";
                    },
                                    {
                        type = "TEXT_DETECTION";
                    }
                );
                image =             {
                    content = "iVBO
          ...........