castiel
castiel

Reputation: 2783

Using jQuery to handle JSON data

I have this little problem with json.

//real json
var json1 = {"test1":"TEST1","test2":"TEST2","test3":"TEST3","test4":"TEST4"};
alert(json.test1); // will echo TEST1
//string, so javascript treat it like a String not JSON
var json2 = "{"test1":"TEST1","test2":"TEST2","test3":"TEST3","test4":"TEST4"}";
alert(json2.test1); // wrong

Now I think you know what I mean, Is there any function or a way to convert that json-like string into a actual JSON?

Upvotes: -1

Views: 199

Answers (4)

Sam Arul Raj T
Sam Arul Raj T

Reputation: 1770

Check this also an another way of JSON Parsing

var json2 = "{"+'"test1"'+":"+'"TEST1"'+","+'"test2"'+":"+'"TEST2"'+","+'"test3"'+":"+'"TEST3"'+","+'"test4"'+":"+'"TEST4"'+"}";

      var jsonObj = $.parseJSON(json2);
      alert(jsonObj.test1);

Upvotes: 0

BenjaminRH
BenjaminRH

Reputation: 12182

There is a very simple way to do this with jQuery:

var jsonObj = jQuery.parseJSON(jsonString);

Of course, you don't need jQuery for this, and you could accomplish the same thing with this:

var jsonObj = JSON.parse(jsonString);

The theory is explained here, and you can also check out the jQuery.parseJSON documentation page.

Upvotes: 2

Phil
Phil

Reputation: 165069

Assuming your string is actually valid, eg (note the single quotes)

var json2 = '{"test1":"TEST1","test2":"TEST2","test3":"TEST3","test4":"TEST4"}';

Use

var jsonObj = JSON.parse(json2);
alert(jsonObj.test1);

Upvotes: 1

Antonio
Antonio

Reputation: 832

You can use eval() function:

var real_json = eval(json2);

Upvotes: 1

Related Questions