Search code examples
muledataweavemule4

How to convert JSON String to JSON in Mule 4?


I am trying to convert below json String to JSON using Dataweave.

"{\n  \"request\": {\n    \"req\": {\n      \"trans\": null,\n      \"search\": null,\n      \"pDayReq\": null,\n      \"cDayReq\": null,\n      \"cDayBal\": {\n        \"id\": \"test\",\n        \"cId\": \"test\",\n        \"bCodes\": [\n          \"090\",\n          \"060\"\n        ],\n        \"formattedDate\": null,\n        \"Date\": \"2023-01-28\",\n        ,\n      \"getReq\": null\n    }\n  }\n}"

read(payload,"application/json") should give us a proper json as an output but it is not working in this case.

Error:

Exception while reading '{
  "request": {
    "r...' as 'application/json' cause by:
Unexpected character ',' at root@[17:9] (line:column), expected '"', while reading `root` as Json.
 
17|         ,
            ^
Trace:
  at main::main (line: 4, column: 1)

I have tried setting up proper mime-type in the code still I don't have any luck.

How can I convert the above json string to the json shown below?

{
  "request": {
    "req": {
      "trans": null,
      "search": null,
      "pDayReq": null,
      "cDayReq": null,
      "cDayBal": {
        "id": "test",
        "cId": "test",
        "bCodes": [
          "090",
          "060"
        ],
        "formattedDate": null,
        "Date": "2023-01-28",
        ,
      "getReq": null
    }
  }

}


Solution

  • The input seems to be a JSON string containing an escaped JSON document. Your intention is to read it as a JSON to retrieve the original JSON document. The problem is that it can not be converted to a valid JSON because the input is not really escaped valid JSON.

    There are two errors in the input string:

    • One extra comma after key "Date"
    • Misses a closing curly bracket at the end

    Fix the input and it will work.