KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Using JSON Pointers
PRODUCT: 4D | VERSION: 16R5 | PLATFORM: Mac & Win
Published On: January 11, 2018

4D v16 R5 introduces a new feature that allows JSON pointers to be used with the JSON based 4D Object data types. 4D implements JSON Pointers based on the IETF standard set. JSON Pointers are used to apply values to an attribute by referencing either another attribute in the same 4D object, or a local JSON file.
The convention to insert a JSON Pointer into the object is to add an attribute with the name "$ref" then the URI of the Pointer in the following format:

{
    "$ref":<path>#<json_pointer>
}

The <path> portion of the URI is only needed if a local JSON file is being referenced and by default is relative to the 4D database's resources folder.

The JSON Pointer can then be evalueated with the new JSON Resolve pointers command.

JSON Pointers are not defined to reference other 4D objects because the object can be referenced directly.

Examples:

Referencing a property within the same object:
{
   "object": {
      "attribute1":1,
      "attribute2":2
   },
   "pointerObj": {
      "$ref": "#/object"
   }
}

The object above is built and then resolved using the new JSON Resolve pointers command
C_OBJECT($object)

$object:=New object
$object.object:=New object("attribute1";1;"attribute2";2)
$object.pointerObj:=New object("$ref";"#/object")

$results:=JSON Resolve pointers($object)


Resulting in
{
   "object": {
      "attribute1":1,
      "attribute2":2
   },
   "pointerObj": {
      "attribute1":1,
      "attribute2":2
   }
}


Referencing a property in a file:
jsonFile.json located in the resources folder contains
{
   "object": {
      "attribute1":1,
      "attribute2":2
   }
}

An object can referece it like so
{
   "pointerObj": {
      "$ref": "#/object"
   }
}

Using 4D code
C_OBJECT($object)

$object.pointerObj:=New object("$ref";"jsonFile.json#/object")

$results:=JSON Resolve pointers($object)

Results in
{
   "pointerObj": {
      "attribute1":1,
      "attribute2":2
   }
}


Just as a reminder on how to reference another 4D Object:
C_OBJECT($object1)
C_OBJECT($object2)

$object1:=New object
$object1.object:=New object("attribute1";1;"attribute2";2)

$object2:=New object("objectRef";$object1.object)

Results are
$object1 contains
{
   "object": {
      "attribute1":1,
      "attribute2":2
   }
}

$object2 contains
{
   "objectRef": {
      "attribute1":1,
      "attribute2":2
   }
}