467,911 Members | 1,375 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 467,911 developers. It's quick & easy.

adding to existing obj using JSON

There's an object:

foo = new Object();

and a property called 'bar' with a value of 1 is to be added to it using
JSON. If I try the following it only demonstrates my ignorance:

var str = "{foo:{bar:1}}";
eval(str);
alert(foo.bar) // gives undefined

Could someone please explain what I'm doing wrong here?
Andrew Poulos
Jul 16 '06 #1
  • viewed: 1534
Share:
1 Reply

Andrew Poulos wrote:
There's an object:

foo = new Object();

and a property called 'bar' with a value of 1 is to be added to it using
JSON. If I try the following it only demonstrates my ignorance:

var str = "{foo:{bar:1}}";
eval(str);
alert(foo.bar) // gives undefined
What you are trying to do is the equivalent of initialising a variable
with an object literal:

var foo = {bar : 1};
Presuming you are using AJAX or similar to return JSONtext, then
depending on how you want do it, you can do:

var JSONtext = '{bar:1}';
var foo = eval( '(' + JSONtext + ')' );

or

eval( 'var foo = ' + JSONtext );
Maybe you want to do:

var JSONtext = 'var foo = {bar:1}';
eval(JSONtext);
Over to you...
--
Rob

Jul 17 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

20 posts views Thread by Luke Matuszewski | last post: by
1 post views Thread by routeslip | last post: by
6 posts views Thread by =?Utf-8?B?U2hhd24gU2VzbmE=?= | last post: by
1 post views Thread by Andrew Burton | last post: by
1 post views Thread by Andrew Poulos | last post: by
23 posts views Thread by dhtmlkitchen | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.