How to Handle a JSON array Whose Elements Contain JSON Objects

How to Handle a JSON array Whose Elements Contain JSON Objects

book

Article ID: KB0078223

calendar_today

Updated On:

Products Versions
TIBCO Streaming 10.x, 7.x

Description

I want to parse the following JSON array in my TIBCO StreamBase/Streaming application:

 [  {   "FieldName1":"value1"   "FieldName2":"value2"  }  {   "FieldName1":"value3"   "FieldName2":"value4"  }  ...  {"FieldName1":"valueN"   "FieldName2":"valueN+1"  } ]

Resolution

The TIBCO Streaming/StreamBase platform can parse json using the parsejson() function, as described in the Help under Home > StreamBase References > StreamBase Expression Language Functions > (sub-heading) Simple Functions: Utilities. This function can parse JSON in either object or array format.  The above example is a JSON [array] whose elements are JSON {objects}.  This combination of JSON array and object formatting (which is valid JSON) needs to be reformatted as follows:
 {  "jsonArray":   [   {    "FieldName1":"value1"    "FieldName2":"value2"   }   {    "FieldName1":"value3"    "FieldName2":"value4"   }   ...   {    "FieldName1":"valueN"    "FieldName2":"valueN+1"   }  ] }
This can be done in a downstream Map operator by replacing the input JSON string with the following settings:

Action: Replace
Field Name: jsonString
Expression: '{"jsonArray":'+input1.jsonString+'}'

..where jsonString is the field name for the input JSON string.

Finally, the parsejson() function can be used in a downstream Map operator using the following settings:

Action: Add
Field Name: parsedJSON
Expression: parsejson(JsonArraySchema(),input1.jsonString) 

..where JsonArraySchema() is a Named Schema defined in the Definitions tab in Studio as follows:

User-added image

This will produce a tuple field parsedJSON with one sub-field named jsonArray.  The jsonArray sub-field is a list of tuples, where the sub-tuple schema ( jsonObjectSchema) holds the values for FieldName1 and FieldName2.

Issue/Introduction

How to Handle a JSON array Whose Elements Contain JSON Objects