9

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?

4
  • 5
    That string is already in JSON format. Do you mean you want to parse it into a JavaScript object? Commented Sep 30, 2020 at 20:35
  • 1
    What about JSON.parse() didn't work? Did you get an error message? Commented Sep 30, 2020 at 20:36
  • Does this answer your question? How to parse JSON string in Typescript Commented Sep 30, 2020 at 20:36
  • Looks like this is ajax call response. You want to use JSON.parse(response.data). Commented Sep 30, 2020 at 20:37

2 Answers 2

25

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
Sign up to request clarification or add additional context in comments.

Comments

0

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);

1 Comment

Re "Try this": An explanation would be in order. E.g., what kind of JSON input is it? Invalid? Valid? The same? Different? What is the idea/gist? What did you change and why? From the Help Center: "...always explain why the solution you're presenting is appropriate and how it works". Please respond by editing (changing) your answer, not here in comments (*** without *** "Edit:", "Update:", or similar - the answer should appear as if it was written today).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.