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:
- Access Advanced View:
- Hold the
Shiftkey and double-click on the JSON Path filter. This action opens the Advanced View.
- Hold the
- Modify Unmarshal Type:
- In the Advanced View, replace the
unmarshalTypevalue withcom.fasterxml.jackson.databind.JsonNode. - Click
Save changesto apply the new settings.
- In the Advanced View, replace the
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
}