如何在 Mule 4 中将引号内有逗号的 CSV 数据转换为 JSON
How to convert a CSV with data having comma inside quotes to JSON in Mule 4
我正在尝试将包含复杂数据的 CSV 文件转换为 JSON,但引号未按预期转换。
以下是我在 Mule 应用程序中的流程:
<flow name="csv-Flow">
<file:listener doc:name="File" directory="${path}" config-ref="File-Inbound" outputMimeType="application/csv; quote='; escape="\"; separator=","; header=true">
<scheduling-strategy>
<fixed-frequency frequency="${frequency}"/>
</scheduling-strategy>
</file:listener>
<set-payload value='#[%dw 2.0
output application/json
---
payload map {
"Name": $."Name",
"Address": $."Address",
"Phone": $."Phone"
}]' doc:name="Set Payload"/>
<logger level="INFO" doc:name="Logger" message="#payload"/>
</flow>
输入 csv:
Name,Address,Phone
xyz,"{""House No"":""SD/123"",""Street"":""First"",""State"":""PA""}",123456789
实际JSON输出:
{
"Name": "xyz",
"Address": "\"{\"\"House No\"\":\"\"SD/123\"\"",
"Phone": "\"\"Street\"\":\"\"First\"\""
}
预期JSON输出:
{
"Name": "xyz",
"Address": "{"House No":"SD/123","Street":"First","State":"PA"}",
"Phone": "123456789"
}
如有任何建议,我们将不胜感激。
将文件侦听器的 outputMimeType 属性更改为:
outputMimeType='application/csv; quote="\""; header=true; escape="\"\""; separator=","'
输出将是:
[
{
"Name": "xyz",
"Address": "{\"House No\":\"SD/123\",\"Street\":\"First\",\"State\":\"PA\"}",
"Phone": "123456789"
}
]
请注意,JSON 需要后退字符 '' 来转义字符串中的引号。您预期的 JSON 输出无效 JSON,因为 Address 中的引号未正确转义。
另请注意,有效负载是 map
函数迭代的数组,因此输出也是 JSON 中的数组。
我正在尝试将包含复杂数据的 CSV 文件转换为 JSON,但引号未按预期转换。
以下是我在 Mule 应用程序中的流程:
<flow name="csv-Flow">
<file:listener doc:name="File" directory="${path}" config-ref="File-Inbound" outputMimeType="application/csv; quote='; escape="\"; separator=","; header=true">
<scheduling-strategy>
<fixed-frequency frequency="${frequency}"/>
</scheduling-strategy>
</file:listener>
<set-payload value='#[%dw 2.0
output application/json
---
payload map {
"Name": $."Name",
"Address": $."Address",
"Phone": $."Phone"
}]' doc:name="Set Payload"/>
<logger level="INFO" doc:name="Logger" message="#payload"/>
</flow>
输入 csv:
Name,Address,Phone
xyz,"{""House No"":""SD/123"",""Street"":""First"",""State"":""PA""}",123456789
实际JSON输出:
{
"Name": "xyz",
"Address": "\"{\"\"House No\"\":\"\"SD/123\"\"",
"Phone": "\"\"Street\"\":\"\"First\"\""
}
预期JSON输出:
{
"Name": "xyz",
"Address": "{"House No":"SD/123","Street":"First","State":"PA"}",
"Phone": "123456789"
}
如有任何建议,我们将不胜感激。
将文件侦听器的 outputMimeType 属性更改为:
outputMimeType='application/csv; quote="\""; header=true; escape="\"\""; separator=","'
输出将是:
[
{
"Name": "xyz",
"Address": "{\"House No\":\"SD/123\",\"Street\":\"First\",\"State\":\"PA\"}",
"Phone": "123456789"
}
]
请注意,JSON 需要后退字符 '' 来转义字符串中的引号。您预期的 JSON 输出无效 JSON,因为 Address 中的引号未正确转义。
另请注意,有效负载是 map
函数迭代的数组,因此输出也是 JSON 中的数组。