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
...........
You can declare an array to check the keys and values of the dictionary and convert it into json object. The for loop stores the value, and the dumps() method stores the dictionary. Check out the below example for a better understanding of the approach.
JSON is a way of representing Arrays and Dictionaries of values ( String , Int , Float , Double ) as a text file. In a JSON file, Arrays are denoted by [ ] and dictionaries are denoted by { } .
JSON FormatJSON at its top-level is a dictionary of attribute/value pairs, or key/value pairs as we've talked about dictionaries in this class. The values are numbers, strings, other dictionaries, and lists.
JSON is a universal (language independent) string-based storage and delivery format that uses a system of nested key/value pairs to encode data. A dictionary (in some languages, including Python) is a data structure that also uses nested key/value pairs.
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)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With