yasarui
yasarui

Reputation: 6553

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?

Upvotes: 8

Views: 34104

Answers (2)

Jordy
Jordy

Reputation: 1960

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

Upvotes: 0

GLJ
GLJ

Reputation: 1144

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

Upvotes: 24

Related Questions