Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.1.0+

Create a JSON Array of Objects

See more JSON Examples

Demonstrates how to create a JSON array of objects.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let arr = CkoJsonArray()!

    let obj = CkoJsonObject()!

    //  Create a new and empty JSON object in the 1st position of the JSON array 
    //  and return the reference in the last argument.
    arr.addObjectAt2(index: 0, json: obj)
    obj.updateString(jsonPath: "Name", value: "Otto")
    obj.updateInt(jsonPath: "Age", value: 29)
    obj.updateBool(jsonPath: "Married", value: false)

    //  Create a new and empty JSON object in the 2nd position of the JSON array 
    //  and return the reference in the last argument.
    arr.addObjectAt2(index: 1, json: obj)
    obj.updateString(jsonPath: "Name", value: "Connor")
    obj.updateInt(jsonPath: "Age", value: 43)
    obj.updateBool(jsonPath: "Married", value: true)

    //  Create a new and empty JSON object in the 3rd position of the JSON array 
    //  and return the reference in the last argument.
    arr.addObjectAt2(index: 2, json: obj)
    obj.updateString(jsonPath: "Name", value: "Ramona")
    obj.updateInt(jsonPath: "Age", value: 34)
    obj.updateBool(jsonPath: "Married", value: true)

    //  Examine what we have:
    arr.emitCompact = false
    print("\(arr.emit()!)")

    //  The output is:

    //  [
    //    {
    //      "Name": "Otto",
    //      "Age": 29,
    //      "Married": false
    //    },
    //    {
    //      "Name": "Connor",
    //      "Age": 43,
    //      "Married": true
    //    },
    //    {
    //      "Name": "Ramona",
    //      "Age": 34,
    //      "Married": true
    //    }
    //  ]

}