Skullbash Skullbash - 4 months ago 61
Swift Question

How to remove square brackets from a dictionary output and replace with curly brackets?

I am a newbie to Swift so kindly excuse me if this question sounds too silly.
I am trying to create a JSON object from a dictionary Array output which must have Curly Brackets("{}") after each entity rather than Square brackets ("[]"). My Code is given below.

import UIKit

var locations = Array<Dictionary<String, String>>()

var myLocations = ["pqr","xyz"]

myLocations.forEach {_ in
var dictionary = Dictionary<String, String>()
dictionary["string1"] = "hello"
dictionary["string2"] = "world"
locations.append(dictionary)

}
print(locations)


The output to this is:- [["string2": "world", "string1": "hello"], ["string2": "world", "string1": "hello"]]\n

However I require it as:- [{"string2": "world", "string1": "hello"}, {"string2": "world", "string1": "hello"}]\n

I know one way of doing this is by using filter Arrays but I suspect there could be an easier way to this which I am not able to find after searching through various documentations on Swift. Could you please help me with this. Thanks in advance.

Answer

The output is

[["string2": "world", "string1": "hello"], ["string2": "world", "string1": "hello"]]

because this is a Swift array of Swift dictionaries.

To convert this object to JSON, do not parse and replace the characters yourself, use NSJSONSerialization instead:

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(locations, options: [])
    if let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding) {
        print(jsonString)
    }
} catch {
    print(error)
}

Prints:

[{"string2":"world","string1":"hello"},{"string2":"world","string1":"hello"}]

We use dataWithJSONObject to convert your Swift object to JSON data, then we use String(data:, encoding:) to convert this JSON data to a JSON string.