KB Article #187820

Retrieving Valid JSON with JSON Path filter and Removing Array Brackets with Scripting Filter

Problem

This article explains how to retrieve a valid JSON object from a JSON Path filter and subsequently remove the surrounding brackets, ensuring that only the JSON content itself is returned.

Resolution

By default, the JSON Path filter returns results in an array format. To obtain a valid JSON object, follow these steps:

  1. Access Advanced View:
    • Hold the Shift key and double-click on the JSON Path filter. This action opens the Advanced View.
  2. Modify Unmarshal Type:
    • In the Advanced View, replace the unmarshalType value with com.fasterxml.jackson.databind.JsonNode.
    • Click Save changes to apply the new settings.
    This configuration change ensures that the JSON Path filter processes the output as a valid JSON object rather than an array.


Step 2: Remove Brackets Using Scripting Filter

To further refine the output and remove any enclosing brackets, use the following Groovy script within a Scripting filter:

import groovy.json.JsonSlurper

import groovy.json.JsonOutput

def invoke(msg) {

// Retrieve the JSON string from the message

def jsonInput = msg.get("my.result").toString()

// Parse the JSON to a list or map

def jsonParser = new JsonSlurper().parseText(jsonInput)

// If the parsed result is a list with a single item, extract that item

if (jsonParser instanceof List && jsonParser.size() == 1) {

jsonParser = jsonParser[0]

}

// Convert the result back to a JSON string and update the message

def resultJson = JsonOutput.toJson(jsonParser)

msg.put("my.result", resultJson)

return true

}