简体   繁体   中英

how to parse a string with escaped json using dataweave 2.0

I need to parse the response of an API that is like this:

"[{\"Customers\":[{\"Id\":1607715391563}],\"Partners\":[],\"ModDate\":\"\\/Date(1608031919597)\\/\",\"CreatedByUserId\":null},{\"Message\":null,\"Code\":\"200\",\"NextPage\":1}]"

I wish I have it like this:

[
   {
      "Customers":[
         {
            "Id":1607715391563
         }
      ],
      "Partners":[
         
      ],
      "ModDate":"/Date(1608031919597)/",
      "CreatedByUserId":null
   },
   {
      "Message":null,
      "Code":"200",
      "NextPage":1
   }
]

I already tried to remove the strings using payload[1 to -2] , and parse the JSON using read(payload[1 to -2], 'application/json') . I already tried to follow some tips of this link but neither worked.

EDIT: The point here is that I want to access, for example, Customers.Id value in other connector, and I can't

how about this?

在此处输入图像描述

%dw 2.0
output application/json
var inpString = "[{\"Customers\":[{\"Id\":1607715391563}],\"Partners\":[],\"ModDate\":\"\\/Date(1608031919597)\\/\",\"CreatedByUserId\":null},{\"Message\":null,\"Code\":\"200\",\"NextPage\":1}]"
---
read(inpString,"application/json")

You can try the following DataWeave expression:

%dw 2.0
output application/json
---
read((payload replace /^"|"$/ with '') replace '\"' with '"', "application/json")

The first replace will remove heading and trailing double quotes, and the second one will replace back slash scaped double quotes by double quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM