6

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yasarui
  • 6,209
  • 8
  • 41
  • 75
  • 2
    That string is already in [JSON format](https://www.json.org/json-en.html). Do you mean you want to parse it into a JavaScript object? – zcoop98 Sep 30 '20 at 20:35
  • 1
    What about `JSON.parse()` didn't work? Did you get an error message? – zcoop98 Sep 30 '20 at 20:36
  • Does this answer your question? [How to parse JSON string in Typescript](https://stackoverflow.com/questions/38688822/how-to-parse-json-string-in-typescript) – gurisko Sep 30 '20 at 20:36
  • Looks like this is ajax call response. You want to use `JSON.parse(response.data)`. – Dipen Shah Sep 30 '20 at 20:37

2 Answers2

21

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
GLJ
  • 1,074
  • 1
  • 9
  • 17
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);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jordy
  • 1,802
  • 2
  • 6
  • 25
  • 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](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/75515547/edit), not here in comments (*** ***without*** *** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Feb 22 '23 at 05:10