I am consulting an API which returns a JSON object and one of the values is badly formatted. It contains \r and \n, when I try to JSON.parse it, it gives me an error. I have tried turning it into a string with JSON.stringify and replace the \r and \n but no luck, it does remove the characters but when i try to parse it again it does not work.
Response
{
"seller_store_name": "test",
"seller_store_description": "<blockquote>
<p>ewffwewef</p>
<p>wefwef</p>
<p> </p>
<table>
<tbody>
<tr>
<td> </td>
<td> </td>
<td>fewfewf</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>efwfewf</td>
</tr>
</tbody>
</table>
</blockquote>",
"seller_profile_picture":"",
"seller_profile_picture_default": "https://test.com/",
"seller_banner": "",
"seller_banner_default": "https://test.com/"
}
Attempt 1, turn to string and remove the \r and \n characters
sellerData = JSON.stringify(e);
" {\n \"seller_store_name\": \"test\",\n \"seller_store_description\": \"<blockquote>\r\n<p>ewffwewef</p>\r\n<p>wefwef</p>\r\n<p> </p>\r\n<table>\r\n<tbody>\r\n<tr>\r\n<td> </td>\r\n<td> </td>\r\n<td>fewfewf</td>\r\n</tr>\r\n<tr>\r\n<td> </td>\r\n<td> </td>\r\n<td>efwfewf</td>\r\n</tr>\r\n</tbody>\r\n</table>\r\n</blockquote>\",\n \"seller_profile_picture\":\"\",\n \"seller_profile_picture_default\": \"https://test.com\",\n \"seller_banner\": \"\",\n \"seller_banner_default\": \"https://test.com\"\n }\n "
sellerData = sellerData.replace(/\\r/g,"").replace(/\\n/g,"");
sellerData = JSON.parse(sellerData);
This successfully removes the characters but when i try to parse the data again, it does not turn into an object, it stays as a string.
Attempt 2, basic parsing When i try to parse it, it gives me an error
sellerData = JSON.parse(String(e));
Unexpected token in JSON at position 126
Any help would be appreciated. Unfortunately, i cannot modify the response from the API.
Try this
sellerData = sellerData.replace(/\\r\\n/g, "");
I think this because of \r\n, so just remove this should be done.
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.