WSO2 EI 6.5.0中Script Mediator解析含特殊字符JSON Payload时触发‘String contains control character’错误的处理咨询
This error pops up because the default Rhino JavaScript engine (used in older WSO2 versions) enforces strict JSON parsing rules—it rejects strings that contain unescaped ASCII control characters (like invisible characters in the 0x00-0x1F range, excluding allowed ones such as \n, \r, \t). Your payload's description or work_notes fields likely picked up these characters from the original email content.
Here are three practical solutions to resolve this issue:
1. Clean Invalid Control Characters Before Parsing
Add a regex replacement to strip out problematic control characters from the payload string before feeding it to JSON.parse. This keeps valid whitespace characters (like newlines and tabs) while removing the ones that break parsing:
var customer_payload = mc.getProperty("decoded_payload"); // Filter out invalid control characters, retain allowed whitespace var cleanedPayload = customer_payload.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, ''); var myJSON = JSON.parse(cleanedPayload); // Proceed with your business logic
The regex targets ASCII control characters 0-8, 11, 12, and 14-31—all of which are disallowed in JSON strings per the official specification.
2. Use Synapse's Native JSON Tools Instead of JavaScript Parsing
WSO2 Synapse has built-in JSON processing capabilities that bypass Rhino's limitations. Instead of parsing the entire payload in JavaScript, extract the specific fields you need directly using Synapse mediators:
For example, to pull the description field:
<!-- Extract the description field before the Script Mediator --> <property expression="json-eval($.ObjectData.description)" name="description" scope="default" type="STRING"/> <script language="js"><![CDATA[ var description = mc.getProperty("description"); // Use the extracted value directly in your logic ]]></script>
This approach leverages Synapse's robust, purpose-built JSON handling, which is far more tolerant of special characters in payload content.
3. Switch to the Nashorn JavaScript Engine
If your WSO2 version supports it (requires Java 8 or newer), replace the outdated Rhino engine with Nashorn. Nashorn has modern, flexible JSON parsing behavior that handles control characters more gracefully. Update your Script Mediator to use nashornjs as the language:
<script language="nashornjs"><![CDATA[ var customer_payload = mc.getProperty("decoded_payload"); var myJSON = JSON.parse(customer_payload); // Your business flow here ]]></script>
In most cases, Nashorn will eliminate the need for manual control character cleaning entirely.
Quick Validation Step
Also double-check that your decoded payload has valid JSON syntax—ensure all double quotes are properly escaped, and there are no unclosed strings. The original payload's HTML entity encoding (") should be fully resolved after the base64Decode step, but confirm this if issues persist.
内容的提问来源于stack exchange,提问作者Justin

