Connecting Tech Pros Worldwide Forums | Help | Site Map

eval to create an object (JSON)

petermichaux@gmail.com
Guest
 
Posts: n/a
#1: Apr 14 '06
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


Martin Honnen
Guest
 
Posts: n/a
#2: Apr 14 '06

re: eval to create an object (JSON)




petermichaux@gmail.com wrote:

[color=blue]
> var s = "{asdf:\"value\"}";[/color]
[color=blue]
> 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())?[/color]

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


--

Martin Honnen
http://JavaScript.FAQTs.com/
petermichaux@gmail.com
Guest
 
Posts: n/a
#3: Apr 14 '06

re: eval to create an object (JSON)



Martin Honnen wrote:[color=blue]
> petermichaux@gmail.com wrote:
>[color=green]
> > var s = "{asdf:\"value\"}";[/color]
>[color=green]
> > 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())?[/color]
>
> 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).[/color]

Thanks Martin, it is working very well now:)

Peter

optimistx
Guest
 
Posts: n/a
#4: Apr 14 '06

re: eval to create an object (JSON)



"Martin Honnen" <mahotrash@yahoo.de> kirjoitti viestissä
news:443fc236$0$18273$9b4e6d93@newsread2.arcor-online.net...[color=blue]
>
> 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).[/color]

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.

---

If I were a doctor in a mental hospital, loosing my temper every now and
then would hardly make the hospital better and get more appreciation for my
knowlege. A friendly attitude would.


Closed Thread