Xbasic

Extension::JsonFormatMapped Method

Syntax

dim reformatted_json as c = extension::Json::FormatMapped(jsonMap as C, json as C)

Arguments

jsonMapCharacter

Specifies the mapping of properties in the source JSON to properties in the desired JSON format.

jsonCharacter

The JSON to format.

Returns

reformatted_jsonCharacter

Returns the JSON reformatted based on the map specification.

Description

Format mapped json (create the structured json).

Discussion

It is sometimes necessary to 'reshape' a JSON document, changing property names, creating arrays and objects from properties, etc.

The extension::JSON::FormatMapped() method allows you to do this.

The method takes two arguments:

  • A map that describes how the JSON should be reshaped (the map is itself a JSON document)
  • A JSON file that contains the JSON data to reshape

For example, consider the following input JSON file:

dim jsonIn as c
jsonIn = <<%str%
{
    "id" : "001",
    "fname" : "John" ,
    "lname" : "Doe",
    "address1" : "12 Main Street",
    "address2" : "Box 20"
}
%str%

Suppose you want to reshape this JSON document so that it looks like the JSON below:

{
    "person": {
        "id": "001",
        "firstname": "john",
        "lastname": "public",
        "address": [
            "12 Main Street",
            "box 20"
        ]
    }
}

To transform the JSON, a Map definition needs to be created. The Map defines how the JSON properties in the source JSON format "map" to properties in the destination JSON format. Map definition shown below would transform the input JSON file above into the desired transformation:

dim jsonMap as c = <<%str%
{
    "person" : {
        "id" : "id" ,
        "firstname" : "fname" ,
        "lastname" : "lname" ,
        "address" : [ "address1" , "address2" ]
    }
}
%str%

Notice that in the input JSON, there is a flat list of properties. The first name and last name properties are called "fname" and "lname".

In the output document, the first name and last name properties are called "firstname" and "lastname", the two address fields are in an array called "address" and all of the properties are now a child of a new object called "person".

Using the Map definition, the input JSON can be transformed into the desired format using the FormatMapped method:

dim jsonOut as c
jsonOut = extension::Json::FormatMapped(jsonmap,jsonin)
jsonOut2 = json_reformat(jsonOut) 'format the JSON