Transform JSON

Provides examples on transforming JSON object within Siddhi.

For all functions available to transform JSON see Siddhi Execution JSON.

define stream InputStream(jsonString string);

from InputStream 
select json:toObject(jsonString) as jsonObj 
insert into PersonalDetails;

from PersonalDetails
select jsonObj, 
    json:getString(jsonObj,'$.name') as name,
    json:isExists(jsonObj, '$.salary') as isSalaryAvailable,
    json:toString(jsonObj) as jsonString 
insert into OutputStream;

from OutputStream[isSalaryAvailable == false]
select 
    json:setElement(jsonObj, '$', 0f, 'salary') as jsonObj
insert into PreprocessedStream;
define stream InputStream(jsonString string);
from InputStream 
select json:toObject(jsonString) as jsonObj 

Transforms JSON string to JSON object which can then be manipulated

insert into PersonalDetails;
from PersonalDetails
select jsonObj, 
    json:getString(jsonObj,'$.name') as name,

Get the name element(string) form the JSON

    json:isExists(jsonObj, '$.salary') as isSalaryAvailable,

Validate if salary element is available

    json:toString(jsonObj) as jsonString 

Stringify the JSON object

insert into OutputStream;
from OutputStream[isSalaryAvailable == false]
select 
    json:setElement(jsonObj, '$', 0f, 'salary') as jsonObj

Set salary element to 0 is not available

insert into PreprocessedStream;

Input

Below event is sent to InputStream,

[

{
    "name" : "siddhi.user",
    "address" : {
        "country": "Sri Lanka",
    },
    "contact": "+9xxxxxxxx"
}

]

Output

After processing, the following events will be arriving:

  • OutputStream:
    [ {"address":{"country":"Sri Lanka"},"contact":"+9xxxxxxxx","name":"siddhi.user"}, siddhi.user, false,
    "{\"name\" : \"siddhi.user\", \"address\" : { \"country\": \"Sri Lanka\", }, \"contact\": \"+9xxxxxxxx\"}"]
  • PreprocessedStream:
    [

    {
        "name" : "siddhi.user",
        "salary": 0.0
        "address" : {
            "country": "Sri Lanka",
        },
        "contact": "+9xxxxxxxx"
    }
    

    ]

Top