admin管理员组

文章数量:1290861

In my application I am getting a response like below:

{"success":true,"data":"{\"status\": \"Failed\", \"percentage_completed\": \"0\", \"actions\": \"Error: Insufficient argument: 1\\n\"}","message":"Logs fetched successfully."}

How can I convert this into JSON? I tried JSON.parse, but it doesn’t seem to work. Is there another way to convert this string into a valid JSON format?

In my application I am getting a response like below:

{"success":true,"data":"{\"status\": \"Failed\", \"percentage_completed\": \"0\", \"actions\": \"Error: Insufficient argument: 1\\n\"}","message":"Logs fetched successfully."}

How can I convert this into JSON? I tried JSON.parse, but it doesn’t seem to work. Is there another way to convert this string into a valid JSON format?

Share Improve this question edited Feb 1, 2024 at 10:56 yasarui asked Sep 30, 2020 at 20:32 yasaruiyasarui 6,5538 gold badges45 silver badges80 bronze badges 4
  • 5 That string is already in JSON format. Do you mean you want to parse it into a JavaScript object? – zcoop98 Commented Sep 30, 2020 at 20:35
  • 1 What about JSON.parse() didn't work? Did you get an error message? – zcoop98 Commented Sep 30, 2020 at 20:36
  • Does this answer your question? How to parse JSON string in Typescript – gurisko Commented Sep 30, 2020 at 20:36
  • Looks like this is ajax call response. You want to use JSON.parse(response.data). – Dipen Shah Commented Sep 30, 2020 at 20:37
Add a comment  | 

2 Answers 2

Reset to default 24

I understand where the confusion is coming from. The provided object has a property which contains a JSON string. In this case, the "data" attribute contains the JSON string which you need to parse. Look at the following example.

var result = {"success":true,"data":"{\"status\": \"Failed\", \"percentage_completed\": \"0\", \"actions\": \"Error: Insufficient argument: 1\\n\"}","message":"Logs fetched successfully."};

JSON.parse(result); // should fail
JSON.parse(result["data"]); // should work
JSON.parse(result.data) // or if you prefer this notation

Try this:

let data = {"success":true,"data":"{\"status\": \"Failed\", \"percentage_completed\": \"0\", \"actions\": \"Error: Insufficient argument: 1\\n\"}","message":"Logs fetched successfully."}
data.data = JSON.parse(data.data);
console.log(data);

本文标签: How to convert a string to JSON in JavaScriptStack Overflow