-1

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?

4
  • Small typo in your first alert of code var json1 = {"test1":"TEST1","test2":"TEST2","test3":"TEST3","test4":"TEST4"}; //change as json1 alert(json1.test1); // will echo TEST1 Commented Feb 15, 2012 at 6:05
  • What does this have to do with jQuery? Commented Feb 15, 2012 at 6:10
  • because I thought in jQuery there must be a way to solve this issue, and jQuery.parseJSON is the way! Commented Feb 15, 2012 at 6:14
  • @DidierGhys I know that even you should be very careful in coding...sometimes this also give you an error........Check out the other way of my answer Commented Feb 15, 2012 at 6:21

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

You can use eval() function:

var real_json = eval(json2);

3 Comments

I tried this way, but it says Syntax Error Unexpected token :
Try eval('(' + json2 + ')'). And make sure your json2 string is escaped properly in your code (it's not in your example).
eval opens a big security hole, because it will process any javascript code. If the string you pass it isn't json, it might cause problems.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.