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

Swap JSON Objects

See more JSON Examples

Demonstrates how to swap two JSON objects within a JSON document.

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oJson
LOCAL nIndex1
LOCAL nIndex2
LOCAL oJsonSara

nSuccess := 0

oJson := CreateObject("Chilkat.JsonObject")
oJson:EmitCompact := 0

//  Load the following JSON:

//  {
//    "petter": {
//      "DOB": "26/02/1986",
//      "gender": "male",
//      "country": "US"
//    },
//    "Sara": {
//      "DOB": "13/05/1982",
//      "gender": "female",
//      "country": "FR"
//    },
//    "Jon": {
//      "DOB": "19/03/1984",
//      "gender": "male",
//      "country": "UK"
//    }
//  }

nSuccess := oJson:LoadFile("qa_data/json/people.json")
IF (nSuccess == 0)
    ? oJson:LastErrorText
    oJson:destroy()
    RETURN
ENDIF

//  Swap the positions of Jon and Sara.
nIndex1 := oJson:IndexOf("Jon")
nIndex2 := oJson:IndexOf("Sara")
oJson:Swap(nIndex1, nIndex2)

//  We have this now:
? oJson:Emit()

//  {
//    "petter": {
//      "DOB": "26/02/1986",
//      "gender": "male",
//      "country": "US"
//    },
//    "Jon": {
//      "DOB": "19/03/1984",
//      "gender": "male",
//      "country": "UK"
//    },
//    "Sara": {
//      "DOB": "13/05/1982",
//      "gender": "female",
//      "country": "FR"
//    }
//  }

//  To swap an inner member:

oJsonSara := CreateObject("Chilkat.JsonObject")
oJson:ObjectOf2("Sara", oJsonSara)

nIndex1 := oJsonSara:IndexOf("DOB")
nIndex2 := oJsonSara:IndexOf("country")
oJsonSara:Swap(nIndex1, nIndex2)

//  We now have this:
? oJson:Emit()

//  {
//    "petter": {
//      "DOB": "26/02/1986",
//      "gender": "male",
//      "country": "US"
//    },
//    "Jon": {
//      "DOB": "19/03/1984",
//      "gender": "male",
//      "country": "UK"
//    },
//    "Sara": {
//      "country": "FR",
//      "gender": "female",
//      "DOB": "13/05/1982"
//    }
//  }

oJson:destroy()
oJsonSara:destroy()