如何在Mule 4中使用DataWeave将JSON字符串转为JSON?
DataWeave解析JSON字符串报错及修复方案
问题背景
尝试用DataWeave将一段JSON字符串转换为JSON对象,原始JSON字符串如下:
"{ \"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 } } }"
使用read(payload,"application/json")执行时触发报错,错误信息如下:
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)
已确认MIME类型设置正确,但问题未解决,需要将原始字符串转换为如下合法JSON:
{ "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 } } } }
报错原因
原始JSON字符串存在语法错误:"Date": "2023-01-28",后多了一个冗余逗号,JSON解析器无法识别这种非法格式,导致read()函数执行失败。
修复方案
方案1:针对固定日期的精准修复
如果Date字段的值固定为2023-01-28,可以用replace函数直接定位并删除冗余逗号:
var cleanedStr = payload replace /(?<="Date": "2023-01-28",)\s*,/ with "" output application/json read(cleanedStr, "application/json")
正则表达式会匹配"Date": "2023-01-28",之后的空白字符加逗号,替换为空字符串来修复语法问题。
方案2:通用冗余逗号修复(适配动态内容)
如果Date字段的值不固定,或者JSON中可能存在多处类似冗余逗号,用通用正则匹配所有合法位置的多余逗号:
var cleanedStr = payload replace /,\s*(?=\s*"[^"]+"\s*:|\s*})/ with "" output application/json read(cleanedStr, "application/json")
该正则会匹配那些后面紧跟键名("key":)或闭合大括号(})的多余逗号,能一次性修复所有同类语法错误。
执行上述代码后,即可得到目标格式的合法JSON对象。
内容的提问来源于stack exchange,提问作者daringfireball
相关产品推荐
相关产品推荐

