Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to JSON in JavaScript

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?

like image 654
yasarui Avatar asked May 09 '26 11:05

yasarui


1 Answers

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
like image 101
GLJ Avatar answered May 11 '26 00:05

GLJ