Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Json in Javascript

'[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]'

When I try to access the above like this:

for (var i = 0; i < data.length; i++) {
    alert(data[i]);
}

It spells out each thing, such as [, {, ", S, and etc.

I also tried doing data[i].SponsorName but obviously got undefined. How should I be accessing this?

like image 727
slandau Avatar asked Apr 30 '26 06:04

slandau


2 Answers

You need to parse the JSON string, preferably with JSON.parse. The JSON API is built into more modern browsers and can be provided to older browsers by including Crockford's JSON script. Crockford's script will detect if the browser already provides the API and adds it if not.

With that in place, if your JSON is in a string variable named response, you can:

var parsedResponse = JSON.parse( response );
//run your iterating code on parsedResponse
like image 193
JAAulde Avatar answered May 02 '26 20:05

JAAulde


You would first need to eval() or more ideally JSON.parse() the JSON string in to a Javascript object. This assumes you trust the source of the JSON.

var jsonobj = JSON.parse(data); 
// Now view the object's structure
console.dir(jsonobj);

Here's what it looks like after being evaluated and printed out:

Screen capture of the JSON obj

like image 35
Michael Berkowski Avatar answered May 02 '26 21:05

Michael Berkowski