slandau
slandau

Reputation: 24052

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?

Upvotes: 3

Views: 15665

Answers (5)

JAAulde
JAAulde

Reputation: 19560

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

Upvotes: 8

Michael Berkowski
Michael Berkowski

Reputation: 270617

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

Upvotes: 2

smoak
smoak

Reputation: 15024

You've got a JSON array followed by an object:

var data = [{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}];

alert(data[0].SponsorID);

Upvotes: 0

Roman
Roman

Reputation: 6428

You parsed the Json string first, right?

var data = '[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]';
data = JSON.parse(data);
alert(data.SponsorName);

JSON.parse, when available, is the preferred method over "eval" because of security and performance issues.

Upvotes: 0

Joe
Joe

Reputation: 82604

var array = JSON.parse('[{"SponsorID":382,"SponsorName":"Test Name","MonthEndReport":true,"AccountingManager":"Me","UnboundProperties":[],"State":16}]')
array[0].AccountingManager; // "me"

Or everyone's favorite library, since IE7 and below don't have native support:

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

Upvotes: 1

Related Questions