views:

59

answers:

3

I'm trying to access JSON data with jQuery and grab a specific set of values based on a variable. I've done this before using [] but for some reason I can't figure out what is going wrong this time.

My JSON file (being read in by getJSON, and named jsonmaker.php) looks like this:

{"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}}

I then have a function which is essentially this:

function addAttrib(attrib) {
$.getJSON("jsonmaker.php", function(data) {
    alert(data[attrib].label);
}
}

But it keeps returning undefined. Any idea what I'm doing wrong? I've checked to make sure the var going to attrib is 0107001, no problems there.

Also, I know my JSON file is a php file so I could filter what's returned to match the attrib value, but I'm looking to develop something that can run purely on HTML and JS, so I could just pack the JSON file for the project and take it with me. No need for a web server w/ PHP etc.

A: 

try to list all properties from data, to have sure the data is being returned:

for (var p in data){
  if (data.hasOwnProperty(p){
    alert(data[p]);
  }
}

It's not your solution but with this you can know how your data is coming.

madeinstefano
+1  A: 

In my experience, $.getJSON() doesn't always return an object. Depending on the MIME type that the server returns along with the JSON, you might end up with a string instead of an object. Check what data contains. If it's a string, you must manually parse it using eval() (old style) or JSON.parse() (new browsers only).

kijin
Also, if the object isn't too complex, try converting it to a string and use alert or prompt to display it so you can see exactly what it is. I usually use JSON.stringify to do that (http://www.json.org/js.html).
Silkster
+1  A: 

The data access itself works for me:

var data = {"0107001":{"label":"Canada","x":"0","y":"0.34"},"0107002":{"label":"USA","x":"-0.16","y":"0.53"}};
var attrib = "0107002";
alert(data[attrib].label); // USA

Make sure that attrib remains untouched between the moment you call addAttrib() and the moment when the AJAX request completes and your anonymous callback function gets called.

Update: is this your real code? You have at least one syntax error:

function addAttrib(attrib) {
    $.getJSON("jsonmaker.php", function(data) {
        alert(data[attrib].label);
    }); // <- Please note missing ");"
}
Álvaro G. Vicario