ShadowMage Posted September 25, 2009 Share Posted September 25, 2009 I've got an interesting situation here. I have a function that constructs a JSON string and then uses the push() method to add the string to an array.This is my function: {"TypeA": [{"Part": '1290', "PcLength": 240, "Pieces": 2}, {"Part": '1290', "PcLength": 180, "Pieces": 2}, {"Part": '1291', "PcLength": 240, "Pieces": 2}, {"Part": '1291', "PcLength": 180, "Pieces": 2}], "TypeB": [{"Part": 'undefined', "PcLength": 176.25, "Pieces": 3}, {"Part": 'undefined', "PcLength": 178.25, "Pieces": 3}, {"Part": 'undefined', "PcLength": 178.25, "Pieces": 3}], "TypeC": [{"Part": 'undefined', "PcLength": 58.4375, "Pieces": 12}, {"Part": 'undefined', "PcLength": 58.4375, "Pieces": 12}, {"Part": 'undefined', "PcLength": 58.4375, "Pieces": 12}], "TypeD": [], "TypeE": [{"Part": '1.000', "PcLength": 86, "Pieces": 3}], "TypeF": []} I cleaned it up a bit so its easier to read. Now it looks like valid JSON but when I try to access arrParts[0]["TypeA"] I get undefined.But get this. I copied and pasted the output from that function to this one to test the JSON syntax: function setArray() { var arrTest = new Array(); strJSON = <JSON output goes here>; arrTest.push(strJSON); alert(arrTest[3]["TypeA"][0]["PcLength"]);} AND IT WORKS!!I don't understand it. Can anyone help me please! What am I doing wrong!Thank you. Link to comment Share on other sites More sharing options...
Ingolme Posted September 25, 2009 Share Posted September 25, 2009 It's because it's a string, not an object.You have to interpret the string, like this: var X = eval(arrParts[0]);alert(X['Type A']); Link to comment Share on other sites More sharing options...
ShadowMage Posted September 25, 2009 Author Share Posted September 25, 2009 Ohhhh! Right, right. Thanks! Sorry, little confusion there between php's json_encode and working with json within javascript. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.