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

Sort JSON Object by Member Key Name

See more JSON Examples

Demonstrates how to sort the members of a JSON object by the key name.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    let json = CkoJsonObject()!

    json.updateString(jsonPath: "xyz", value: "1234")
    json.updateString(jsonPath: "abc.xyz", value: "1234")
    json.updateString(jsonPath: "abc.def", value: "1234")
    json.updateString(jsonPath: "abc.aaa", value: "1234")
    json.updateString(jsonPath: "ghi", value: "1234")
    json.updateString(jsonPath: "nmo", value: "1234")

    json.emitCompact = false
    print("\(json.emit()!)")

    //  This is our initial JSON:

    //  {
    //    "xyz": "1234",
    //    "abc": {
    //      "xyz": "1234",
    //      "def": "1234",
    //      "aaa": "1234"
    //    },
    //    "ghi": "1234",
    //    "nmo": "1234"
    //  }

    //  Sort the top-level JSON object by key.
    var ascending: Bool = true
    var caseSensitive: Bool = true
    json.sort(ascending: ascending, caseSensitive: caseSensitive)

    //  Look at the sorted JSON..
    print("\(json.emit()!)")

    //  {
    //    "abc": {
    //      "xyz": "1234",
    //      "def": "1234",
    //      "aaa": "1234"
    //    },
    //    "ghi": "1234",
    //    "nmo": "1234",
    //    "xyz": "1234"
    //  }

    //  Now sort the members of the "abc" object..
    let jsonAbc = CkoJsonObject()!
    json.objectOf2(jsonPath: "abc", jsonObj: jsonAbc)

    jsonAbc.sort(ascending: ascending, caseSensitive: caseSensitive)

    //  Now look at the JSON with the members under "abc" also sorted..
    print("\(json.emit()!)")

    //  {
    //    "abc": {
    //      "aaa": "1234",
    //      "def": "1234",
    //      "xyz": "1234"
    //    },
    //    "ghi": "1234",
    //    "nmo": "1234",
    //    "xyz": "1234"
    //  }

}