I'm trying to encode a [[String : String]]
into JSON nested objects with JSONEncoder()
.
Example of Swift output:
[["firstName": "John", "lastName": "Doe"], ["firstName": "Tim", "lastName": "Cook"]]
Intended output of JSON after being encoded:
[
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Tim",
"lastName": "Cook"
}
]
How would I go about looping through this array of dictionaries and then encoding it with JSONEncoder().encode()
? Thanks so much!
CodePudding user response:
JSONEncoder gives you Data
by default. To get it back into String
form, you can use this:
let input = [["firstName": "John", "lastName": "Doe"], ["firstName": "Tim", "lastName": "Cook"]]
do {
let json = try JSONEncoder().encode(input)
print(String(decoding: json, as: UTF8.self))
} catch {
print(error)
}
Which yields:
[{"firstName":"John","lastName":"Doe"},{"firstName":"Tim","lastName":"Cook"}]
CodePudding user response:
Using Codable
to encode/decode JSON data. Firstly, convert JSON into an object like this, it will make it easier if you update with more fields:
struct Person: Codable {
var firstName: String
var lastName: String
}
Assume that you have a Person
array
var persons = [Person]()
persons.append(.init(firstName: "John", lastName: "Doe"))
persons.append(.init(firstName: "Tim", lastName: "Cook"))
//PRINT OUT
let jsonData = try! JSONEncoder().encode(persons)
let jsonString = String(data: jsonData, encoding: .utf8)
And this is the output:
"[{"firstName":"John","lastName":"Doe"},{"firstName":"Tim","lastName":"Cook"}]"