1

我有一个数组

     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
        )

)

我将 javascript 函数中的数组作为json_encode.

请任何人都可以帮助我在 javascript 中阅读此 JSON。

 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"}
}

我想从上面读取地址。

提前感谢您的帮助。

4

6 回答 6

2

一种方法是使用检索值的索引方式。就像是:

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

你甚至可以这样做:

var addr = info["1"]["address"];

JSFiddle:http: //jsfiddle.net/infiniteloops/2sTY6/

于 2013-05-30T06:53:10.030 回答
1

大多数浏览器都支持 JSON.parse(),它是在 ECMA-262 第 5 版(JS 所基于的规范)中定义的。它的用法很简单:

var json = '{"result":xyz,"count":1}',
obj = JSON.parse(json);

  alert(obj.count);

对于不支持的浏览器,您可以使用json2.js来实现它。

于 2013-05-30T06:53:23.723 回答
1
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"]));

见样品;http://jsfiddle.net/DHeUL/

于 2013-05-30T06:59:43.650 回答
0

像下面这样:

info[1].address
info[2].address

但是您可以考虑使用数组而不是这样的对象。

于 2013-05-30T06:52:57.583 回答
0

这应该可以解决问题:

for(i in info){
    data=info[i];
    console.log("title: "+data.title+"\taddress: "+data.address);
}
于 2013-05-30T07:00:01.573 回答
0

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.
						
	}
					
}
给定代码的输出

于 2015-12-24T17:27:47.817 回答