2

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.

1
  • When you look at the "data" variable in Firebug or the IE debugger, what does it contain? Commented Oct 28, 2010 at 14:01

3 Answers 3

3

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 ");"
}
Sign up to request clarification or add additional context in comments.

Comments

1

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).

1 Comment

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 (json.org/js.html).
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.