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

Get the Root of a JSON Document

See more JSON Examples

Demonstrates how to get back to the JSON root object from anywhere in the JSON document. This example uses the following JSON document:
{
  "flower": "tulip",
  "abc":
    {
    "x": [
       { "a" : 1 },
       { "b1" : 100, "b2" : 200 },
       { "c" : 3 }
    ],
    "y": 200,
    "z": 200
    }
}

Chilkat Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oJson
LOCAL cJsonStr
LOCAL oAbcObj
LOCAL oXArray
LOCAL oBObj
LOCAL oDocRoot

nSuccess := 0

oJson := CreateObject("Chilkat.JsonObject")

cJsonStr := '{"flower": "tulip","abc":{"x": [{ "a" : 1 },{ "b1" : 100, "b2" : 200 },{ "c" : 3 }],"y": 200,"z": 200}}'

nSuccess := oJson:Load(cJsonStr)
IF (nSuccess == 0)
    ? oJson:LastErrorText
    oJson:destroy()
    RETURN
ENDIF

//  Get the "abc" object.
oAbcObj := CreateObject("Chilkat.JsonObject")
nSuccess := oJson:ObjectOf2("abc", oAbcObj)
IF (nSuccess == 0)
    ? oJson:LastErrorText
    oJson:destroy()
    oAbcObj:destroy()
    RETURN
ENDIF

//  Side note: The JSON of a sub-part of the document can be emitted from any JSON object:
oAbcObj:EmitCompact := 0
? oAbcObj:Emit()

//  Navigate to the "x" array
oXArray := CreateObject("Chilkat.JsonArray")
oAbcObj:ArrayOf2("x", oXArray)

//  Navigate to the 2nd object contained within the array.  This contains members b1 and b2
oBObj := CreateObject("Chilkat.JsonObject")
oXArray:ObjectAt2(1, oBObj)

//  Show that we're at "b1/b2".
//  The value of "b1" should be "200"
? "b2 = " + Str(oBObj:IntOf("b2"))

//  Now go back to the JSON doc root:
oDocRoot := CreateObject("Chilkat.JsonObject")
oBObj:GetDocRoot2(oDocRoot)

//  We'll skip the null check and assume it's non-null...

//  Pretty-print the JSON doc from the root to show that this is indeed the root.
oDocRoot:EmitCompact := 0
? oDocRoot:Emit()

oJson:destroy()
oAbcObj:destroy()
oXArray:destroy()
oBObj:destroy()
oDocRoot:destroy()