Parse and build JSON in Teneo Studio

JSON parsing

In Teneo Studio, you can use the JsonSlurper class to read in JSON formatted data which is a very common format for structured documents and API call responses. The JsonSlurper class is already included in Groovy 3 so you just need import it using the following code:

import groovy.json.JsonSlurper

Suppose that you have the following JSON saved in a string named sJson:

def sJson= '''
{
    "jobtitle":"System Developer",
    "location":"New York",
    "applicants":
    [
        {
            "name":"Tommy",
            "programming_languages":
            [
                "Groovy",
                "Python",
                "Java"
            ]
        },
        {
            "name":"John",
            "programming_languages":
            [
                "Ruby",
                "php"
            ]
        }
    ]
}
'''

Use the following code to parse this JSON and save it in a map called mParsedJson:

def mParsedJson = new JsonSlurper().parseText(sJson)

See the class of mParsedJson and its content below:

If you have the JSON file uplodaded in your Resource files, please use the following code to parse it:

URL url = this.getClass().getClassLoader().getResource('your_file.json');
URI uri = url.toURI();
File file = new File(uri);
def mParsedJson = new JsonSlurper().parseText(file.getText())

JSON building

You can also user the JsonBuilder class to convert a string, list or map object to a JSON formatted string which is required by the message types of Teneo Web Chat and is also widely used in other kinds of frontend s. Same as JsonSlurper, you need to import the JsonBuilder class as well before you call it in your code:

import groovy.json.JsonBuilder

Then use the following code to build the JSON string. Let’s take the variable mParsedJson we have just created:

def JSON = new JsonBuilder(mParsedJson).toString()

You will get the same JSON string as we defined in the variable sJson before:

This code in this post is an example on how you can parse and build JSON formatted data in your Teneo solution. You can find another post here which shows an example on how to parse YAML formatted data, and here for XML formatted data. Hope this post can help in your journey with Teneo Studio!

1 Like