Duffy Dolan Duffy Dolan - 11 months ago 36
JSON Question

How can I access a specific json object using jquery and json?

I'm having a problem trying to return a specific record using jQuery and JSON. I'm passing a variable to the function and want to output only the data matching the id I've set when the function is executed.

Right now, my function looks like this:

function getEffectsData(myNum){
$.getJSON("jsonscript.php", { id: +myNum },function(data){
var x = data.x;

The JSON output looks like this:

{"stuff": [ { "id":1, "x":3, "y":6, "z":-6 },{ "id":2, "x":2, "y":7, "z":-3 }]}

The only thing I know is that the correct variable is being passed to the function. After that, nothing happens. Very new at this, so any help is greatly appreciated.

I appreciate everybody's input on this. To clarify, I am trying to return the data from only the object that's id matches myNum. I want to be able to access all of the data from that object, but only that object. I have no idea where that object will be in the array. I simplified the ids and the data in my question to help clarify the problem.

Thanks again.


You can access x from your JSON like this:

var x1 = data.stuff[0].x; // the first object's x key
var x2 = data.stuff[1].x; // the second object's x key

Because your JSON tree looks like this:

{ // base object
    "stuff": [ // array
    { // 0.: object
        "id": 1,  // key => value
        "x" : 3,  // key => value
        "y" : 6,  // key => value
        "z" : -6  // key => value
    { // 1.: object
        "id": 2,  // key => value
        "x" : 2,  // key => value
        "y" : 7,  // key => value
        "z" : -3  // key => value

So with data.stuff[0].x you select stuff object then it's first element and then its x key.

But If you want to handle all the x key for example, then you need to loop through the stuff array by a simple for loop or the $.each method.


As for your question. If you want to get the object with id myNum you have 2 possibilities:

  1. if you possess jsonscript.php you can send the data only with the correct id from the server, because you pass the id to it by { id: +myNum } which is the second parameter of getJSON

  2. You loop through the data until you find the object with the correct id

    var object; 
    $.each(data.stuff, function(i, obj) {
      if (obj.id === myNum) object = obj;
    // now object is the one with the right id