Skip to content

TupleToJSON Operator

natashadsilva edited this page May 21, 2020 · 13 revisions

The TupleTOJSON operator can be used to convert SPL tuples to JSON strings.

Quick Examples

Examples

Simple Conversion

In this example, the JsonS stream attribute jsonString will have the value

{"name" : "Jane", "age": 25, "relatives" : ["John", "Sam" ] }

  stream<rstring name, int32 age, list<rstring> relatives> InputS = Beacon() {
    param
      iterations : 1u;
    output InputS : name = "Jane", age = 25, relatives = ["John", "Sam"];
  }
  stream<rstring jsonString> JsonS = TupleToJSON(InputS) {}

Converting part of the SPL tuple

You can optionally specify an attribute of the SPL tuple to be converted to JSON. In the following example we have this input tuple: { name = "John", address = { state= "NY", country = "USA" } }

But the output JSON is only the address part:

{ "state" : "NY", "country" : "USA" }

Note that this only works on first level attributes.

type AddressType = rstring state, rstring country;
type PersonType = rstring name, AddressType address;

stream<PersonType> InputS = Beacon() {
  param 
    iterations : 1u;
  output InputS : 
    InputS = { name = "John", address = { state= "NY", country = "USA" } };
}

stream<rstring jsonString> JsonS = TupleToJSON(InputS) {
  param 
    rootAttribute : "address";
}

JSON Arrays as Output

In this example, the JsonS stream attribute jsonString will be an array containing this value ["John", "Sam" ]

Note that the list can contain any supported SPL type.

  stream<list<rstring> relatives> InputS = Beacon() {
    param
      iterations : 1u;
    output InputS : relatives = ["John", "Sam"];
  }
  stream<rstring jsonString> JsonS = TupleToJSON(InputS) {
    rootAttribute : "relatives";
  }

Namespace

com.ibm.streamsx.json

Parameters

Following parameters are supported

jsonStringAttribute
This is an optional parameter that can be used to specify the name of the output stream attribute that should be populated with the JSON string. By default, the operator expects an attribute named "jsonString" to be present in the output stream. This attribute can be either of USTRING or RSTRING type.

rootAttribute This is an optional parameter that can be used to specify the name of an inner attribute of the input stream to be used as the root of the SPL type to be converted to JSON. By default, the base of the input stream tuple is used to convert to JSON

Reference

SPLDoc