PDA

View Full Version : JSON Help



vatech1993
14 Dec 2006, 8:18 PM
I'm sure I'm missing the obvious, but I've spent too long trying to figure this out by myself, so here goes...

Listed below is a code snippit. Basically I take a json string and load it into a variable called data. I dynamically add a new line instance to my object graph, but when I try viewing the value after using the encode method it does not show my new value, it instead shows just []. If I try accessing the new value directly (the second alert) the newly created value is returned. What am I missing here? Did I add the new line object incorrectly? Or am I using the encode method incorrectly? Thanks in advance.



var data = eval("({'key':46100,'lines':[{'lineid':209859,'desc':'test'}]})");
var line = [];
newRow--;
line.lineid = newRow;
line.desc = "abc";
data.lines.push(line);

alert(YAHOO.ext.util.JSON.encode(data));
alert(data.lines[1].lineid);

jack.slocum
14 Dec 2006, 8:29 PM
var line = []; creates line as an array.

line.lineid = newRow; adds an dynamic property to the array (perfectly legal for all js objects, but it doesn't actually become part of the array).

YAHOO.ext.util.JSON.encode(data) treats line as an array since that's how it was defined. Since no items were added to the array, it returns an empty array [].

If you change var line = []; to var line = {}; you will create an object instead of an array and you will get the desired behavior.