eval to create an object (JSON)

P

petermichaux

Hi,

I am gambling my soul and playing with eval(). I think this is similar
to JSON.

This script

var s = "{asdf:\"value\"}";
var o = eval(s);
var str = [];
for(p in o){
str.push(p + ":" + o[p]);
}
document.write("{" + str.join(", ") + "}");

outputs

{0:v, 1:a, 2:l, 3:u, 4:e}

but I expected

{asdf:value}

What's am I doing wrong (besides using eval())?

Thanks,
Peter
 
M

Martin Honnen

var s = "{asdf:\"value\"}";
outputs

{0:v, 1:a, 2:l, 3:u, 4:e}

but I expected

{asdf:value}

What's am I doing wrong (besides using eval())?

You need to use
var o = eval('(' + s + ')');
to ensure the curly braces are interpreted as the delimiters of an
object initializer (and not as block statement delimiters with one
labelled statement).
 
P

petermichaux

Martin said:
You need to use
var o = eval('(' + s + ')');
to ensure the curly braces are interpreted as the delimiters of an
object initializer (and not as block statement delimiters with one
labelled statement).

Thanks Martin, it is working very well now:)

Peter
 
O

optimistx

Martin Honnen said:
You need to use
var o = eval('(' + s + ')');
to ensure the curly braces are interpreted as the delimiters of an
object initializer (and not as block statement delimiters with one
labelled statement).

Thanks for the friendly and thorough answer. I had long wondered the reason
for parenthesis.
It has been a pleasure to read your posts, because of the human, polite and
emphatetic attitude.

After reading some robotlike or aggresive harsh comments every now and then
from some techically knowledgeable people your professional style saves my
day. Thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top