0

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"
                }
            ]
        }
    ]
}
2
  • What are you specifically asking and what do you mean by "JSON array"? Is this a server side swift question or an iOS app question or something else? Commented Apr 30, 2019 at 11:43
  • server side swift question Commented Apr 30, 2019 at 12:13

1 Answer 1

2

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response, how to insert "ObjectsHere" in the above code and how to append the value into Test2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.