adding to existing obj using JSON

A

Andrew Poulos

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
 
R

RobG

Andrew said:
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...
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top