Best way to find data in json by jquery
I tried this but didn't work and got an error SyntaxError: Invalid property identifier
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);
});
+3
source to share
3 answers
Keys are case sensitive, which is why id
they id
differ. Also fix your JSON array. Try the following:
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 a jsfiddle .
+4
source to share
Your json array is not valid:
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);
});
+2
source to share
you created an 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 @Beginner's answer mentioned, you need to take care of the key case. Keys are case sensitive
+1
source to share