elgoog Posted May 22, 2009 Share Posted May 22, 2009 I have been trying to find the simplest examples to parse JSON, and can't get any to work http://www.json.org/json2.js <html> <head> <title>Parsing Message using JSON in JavaScript</title> <script language="javascript" src="json2.js"></script> <script language="javascript" > var students = { "Maths" : [ { "Name" : "Amit", // First element "Marks" : 67, "age" : 23 }, { "Name" : "Sandeep", // Second element "Marks" : 65, "age" : 21 } ] } // Printing Maths array values in the alert message var i=0 var arrayObject = new Array(); for(i=0;i<students.Maths.length;i++) { arrayObject.push(students.Maths[i].Name); arrayObject.push(students.Maths[i].Marks); arrayObject.push(students.Maths[i].age); } alert("Parsing JSON Message Example "); alert(students.Maths[i].Name); alert(arrayObject.toJSONString().parseJSON()); alert("Parsing JSON Message Example "); </script> </head> <body> Parsing Message using JSON in JavaScript </body> </html> The example above is not working for me, only the first alert pop's up. I have also tried var people = { "programmers": [ { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }, { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" }, { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" } ], "authors": [ { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" }, { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" }, { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" } ], "musicians": [ { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" }, { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" } ] } alert(people.programmers[0].lastName); Can someone please provide me with a simple example of a JSON structured variable, with a simple alert message that accesses something in between? Not sure what i am doing wrong Quote Link to comment Share on other sites More sharing options...
Ken2k7 Posted May 22, 2009 Share Posted May 22, 2009 alert(students.Maths[i].Name); alert(arrayObject.toJSONString().parseJSON()); 1. var i is undefined. It's only available inside the for loop, so that alert fails. 2. toJSONString() is not a method I know of as pre-defined. I can be wrong. Your last example should work. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.