Reputation: 104
I have an array
Array
(
[1] => Array
(
[title] => Graslei BVBA
[address] => Belgium Bent
)
[2] => Array
(
[title] => Red Poppy SPRL
[address] => Belgium 4900 Spa
)
[3] => Array
(
[title] => Loula Bee
[address] => Belgium Liege
)
)
I pass array in javascript function as json_encode
.
Please anybody can help me to read this JSON in javascript.
var info = {
"1":{"title":"Graslei BVBA","address":"Belgium Bent"},
"2":{"title":"Red Poppy SPRL","address":"Belgium 4900 Spa"},
"3":{"title":"Loula Bee","address":"Belgium Liege"}
}
I want address from above to be read.
Thanks for help in advance.
Upvotes: 1
Views: 229
Reputation: 89
var info = {
"1":{"title":"Graslei BVBA","address":"Belgium Bent"},
"2":{"title":"Red Poppy SPRL","address":"Belgium 4900 Spa"},
"3":{"title":"Loula Bee","address":"Belgium Liege"}
}
for(var obj in info){ //repeats all the objects of "info"
console.log("obj: "+obj);//prints "1","2","3" in the console
for(var key in info[obj]){//repeats all the objects of "info[obj]"
console.log("key: "+key);//key is "title","address" of info[obj]
console.log("value: "+info[obj][key]);//value "Graslei BVBA" for info["1"]["title"] and so on.
}
}
Upvotes: 0
Reputation: 2533
var info = {"1":{"title":"Graslei BVBA","address":"Belgium Bent"},"2":{"title":"Red Poppy SPRL","address":"Belgium 4900 Spa"},"3":{"title":"Loula Bee","address":"Belgium Liege"}};
/*
* info[number][string]
*/
info[1] // Object {title: "Graslei BVBA", address: "Belgium Bent"}
info[1]["address"] // "Belgium Bent"
// for
for (var i in info) (function(title, address) {
console.log(title, address); // print title and address
}(info[i]["title"], info[i]["address"]));
see sample; http://jsfiddle.net/DHeUL/
Upvotes: 1
Reputation: 5676
This should do the trick:
for(i in info){
data=info[i];
console.log("title: "+data.title+"\taddress: "+data.address);
}
Upvotes: 0
Reputation: 3057
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":xyz,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
Upvotes: 1
Reputation: 7121
One way to do this would be to use the index way of retrieving the value. Something like:
var info = {"1":{"title":"Graslei BVBA","address":"Belgium Bent"},"2":{"title":"Red Poppy SPRL","address":"Belgium 4900 Spa"},"3":{"title":"Loula Bee","address":"Belgium Liege"}};
$('P').append(info["1"].address);
You could even do this:
var addr = info["1"]["address"];
JSFiddle: http://jsfiddle.net/infiniteloops/2sTY6/
Upvotes: 2
Reputation: 160833
Like the below:
info[1].address
info[2].address
But you may consider use an array instead of such object.
Upvotes: 0