Convert string to json array

I get this response from an Ajax request. Javascript seems to intepret this as a string. (When I say alert this.responseText, the whole line is displayed)

How can I convert it to a javascript object (JSON)?

{"response": {
   "success": "The activity has been removed",
   "message": "0"

  }
}

I do not use jquery.

+3
source share
3 answers

This is not the safest thing in the world, but you can do it:

var value = null, txt = this.responseText;
eval("value = (" + txt + ")");

This might be a little safer:

var value = null, txt = this.responseText;
!function(window) { eval("value = (" + txt + ")"); }();

but there are still all kinds of potential hacks. You better use a library.

+2
source

If you are using jQuery, JSON.parse(this.responseString);or jQuery.parseJSON(this.responseString);should work.

+15
source
+2

Source: https://habr.com/ru/post/1768288/


All Articles