Mou
Mou

Reputation: 16292

Best way to find data in json by jquery

i tried this but did not work and getting error SyntaxError: invalid property id

js fiddle link http://jsfiddle.net/mm49u6wv/

var data={
 { "Id": "12345", "Name": "Acme Widget 1", "Price": "£25.99", "Status": "In Stock"  },
 { "Id": "67890", "Name": "Acme Widget 2", "Price": "£28.99", "Status": "In Stock"  },
 { "Id": "11123", "Name": "Acme Widget 3", "Price": "£15.99", "Status": "In Stock"  },
 { "Id": "14156", "Name": "Acme Widget 4", "Price": "£33.99", "Status": "In Stock"  }
}

$.each(data, function(i, v) {
    alert(v.id);
});

Upvotes: 3

Views: 40

Answers (3)

Nishit Maheta
Nishit Maheta

Reputation: 6031

you created invalid JSON array. DEMO

  var data=[
    { "Id": "12345", "Name": "Acme Widget 1", "Price": "£25.99", "Status": "In Stock"  },
    { "Id": "67890", "Name": "Acme Widget 2", "Price": "£28.99", "Status": "In Stock"  },
    { "Id": "11123", "Name": "Acme Widget 3", "Price": "£15.99", "Status": "In Stock"  },
    { "Id": "14156", "Name": "Acme Widget 4", "Price": "£33.99", "Status": "In Stock"  }
];


 $.each(data, function(i, v) {
   alert(v.Id);
 });

As mentioned in @Beginner answer you need to take care of key case. Keys are case sensitive

Upvotes: 1

Abhishekh Gupta
Abhishekh Gupta

Reputation: 6236

Keys are case sensitive so id and Id are different. Also correct your JSON array. Try this:

var data= [
 { "Id": "12345", "Name": "Acme Widget 1", "Price": "£25.99", "Status": "In Stock"  },
 { "Id": "67890", "Name": "Acme Widget 2", "Price": "£28.99", "Status": "In Stock"  },
 { "Id": "11123", "Name": "Acme Widget 3", "Price": "£15.99", "Status": "In Stock"  },
 { "Id": "14156", "Name": "Acme Widget 4", "Price": "£33.99", "Status": "In Stock"  }
];

$.each(data, function(i, v) {
    alert(v.Id);
});

Here is the jsfiddle.

Upvotes: 4

Arsh Multani
Arsh Multani

Reputation: 1591

Your json array is invalid it should be :

var data=[
 { "Id": "12345", "Name": "Acme Widget 1", "Price": "£25.99", "Status": "In Stock"  },
 { "Id": "67890", "Name": "Acme Widget 2", "Price": "£28.99", "Status": "In Stock"  },
 { "Id": "11123", "Name": "Acme Widget 3", "Price": "£15.99", "Status": "In   Stock"  },
 { "Id": "14156", "Name": "Acme Widget 4", "Price": "£33.99", "Status": "In Stock"  }
];

and inside $.each id should be Id :

$.each(data, function(i, v) {
alert(v.Id);
});

Upvotes: 2

Related Questions