Reputation: 7
How to append one new value in JSON array using the below format
https://next.json-generator.com/api/json/get/NJC7eX-oU
In the above URL how to append the data letters array??
{
"Letters": [
{
"Test1": [
{
"Priority": 1,
"Description": "A"
},
{
"Priority": 2,
"Description": "B"
}
],
"Test2": [
{
"Priority": 1,
"Description": "A"
}
]
}
]
}
Upvotes: 0
Views: 342
Reputation: 100503
You need to decode it with
struct Root: Codable {
var letters: [[String:[Test]]]
enum CodingKeys: String, CodingKey {
case letters = "Letters"
}
}
struct Test: Codable {
let priority: Int
let description: String
enum CodingKeys: String, CodingKey {
case priority = "Priority"
case description = "Description"
}
}
do {
var res = try JSONDecoder().decode(Root.self, from:data)
res.letters.append(["test3":[Test(priority: 6, description: "des")]])
res.letters[0]["Test2"]?.append(Test(priority: 612, description: "des2"))
let wer = try JSONEncoder().encode(res)
let json = String(data: wer, encoding: .utf8)
print(json)
}
catch {
print(error)
}
Upvotes: 2