-1

I have been playing around with JSON a little, but I found something I don't quite understand, for example, I have this piece of code:

var str = "{'name':'vvv'}";                    
var cjson = eval ("(" + str + ")");
alert(cjson.name);

It works fine, but with this piece of code

var str = "{'name':"+'vvv'+"}";    
var cjson = eval ("(" + str + ")");
alert(cjson.name);

It does not, I got the following firebug error : ReferenceError: vvv is not defined.

Why doesnt it works with the second way, isnt str a valid string in both cases?

2
  • That's not valid JSON, double quotes are required. Commented Aug 27, 2013 at 1:21
  • You need to add quotes around 'vvv', after string concatenation you get var str = "{'name':vvv}"; You should have something like var str = "{'name':"+ "'vvv'" +"}"; Commented Aug 27, 2013 at 1:38

2 Answers 2

3

It's a string, yes. But not the same string, and not valid JSON.

 var str = "{'name':" + 'vvv' + "}";

is the same as:

 var str = "{'name':" + "vvv" + "}";

which is the same as:

 var str = "{'name':vvv}";

When you try to evaluate that, it's as if you'd declared:

 var cjson = { 'name': vvv };

and you have no variable named vvv.

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

1 Comment

For the record, valid JSON would be var str = '{"name": "vvv"}';
0

when you do var str = "{'name':"+'vvv'+"}";, the generated string is "{'name':vvv}" where vvv is not a string literal. So the eval will try to resolve it in the execution scope, since it is not found there it throws an error

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.