javascript 使用 jQuery 访问多维 JSON 数组中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5617496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:47:13  来源:igfitidea点击:

Accessing data in a multidimensional JSON array with jQuery

javascriptjqueryarraysjsonajax

提问by dangermark

I am trying to work out how to access data in an essentially multidimensional JSON array.

我正在尝试研究如何访问本质上是多维 JSON 数组中的数据。

My jQuery AJAX request looks like this:

我的 jQuery AJAX 请求如下所示:

 $("#login-form").submit(function(e) {
 e.preventDefault();
 $.ajax({
   type: 'POST',
   url: '/ajax/login',
   data: 'email='+$("#email").val()+'&password='+$("#password").val(),
   success: function(data){

     // FIRE ALERT HERE        
     alert(data.firstname);

     },
     dataType: 'json'
  });
});

This is what i am getting back. User account details, plus a list of products they have against their account.

这就是我要回来的。用户帐户详细信息,以及他们针对其帐户拥有的产品列表。

{
    "logged_in":true,
    "firstname":"Joe",
    "surname":"Bloggs",
    "Full_name":"Joe Bloggs",
    "email":"[email protected]",
    "phone":"+123456789",
    "website":"",
    "age":"26-35",
    "street":"1 Street Ave",
    "city":"Townland",
    "state":"NA",
    "postcode":"1234",
    "country":"Australia",
    "products":2,
    "0":{
        "product_no":"1087",
        "customer":"2",
        "bought_from":"1",
        "date_of_purchase":"2011-04-08",
        "method":"instore",
        "invoice":"0",
        "current":"1"
    },
    "1":{
        "product_no":"24",
        "customer":"2",
        "bought_from":"1",
        "date_of_purchase":"2011-04-08",
        "method":"instore",
        "invoice":"0",
        "current":"1"
    }
}

As you can see, i am alerting the first name, which is fine. I can access everything in the first dimension by using data.key but i'm not sure how then i need to index the next dimension. Obviously I would like to display each of the products somehow.

如您所见,我正在提醒名字,这很好。我可以使用 data.key 访问第一个维度中的所有内容,但我不确定我需要如何索引下一个维度。显然,我想以某种方式展示每个产品。

Suggestions would be most welcome.

建议将是最受欢迎的。

采纳答案by Salman A

Inside your success function you can treat the JSON data as a JavaScript object. You can access the product array and objects inside it like this:

在您的成功函数中,您可以将 JSON 数据视为 JavaScript 对象。您可以像这样访问产品数组和其中的对象:

console.log(data.products + " product(s) in data"); // data.products is 2 (integer)
for(var i = 0; i < data.products; i++) {            // 
    var product = data[i.toString()];               // 0.toString() is "0"
                                                    // data["0"] is what you want
                                                    // now product points to the property "0"
    console.log(product.product_no);                // so you can use product.xxx
                                                    // or product["xxx"]
}                                                   // likewise for "1", "2", "3" and so on

Replace console.logwith alertif you do not know what console is.

更换console.logalert,如果你不知道控制台是什么。

回答by Daniel Protopopov

Each of the product details can be accessed through data[iProductIndex.toString()]member. Data is stored inside data["0"]and data["1"], therefore to access them you need to convert integer value to string. Unfortunately you won't be able to use $.eachloop because "0" and "1" are separate member objects. Use for loop with iProductIndex.

每个产品的详细信息都可以通过data[iProductIndex.toString()]会员访问。数据存储在data["0"]and 中data["1"],因此要访问它们,您需要将整数值转换为字符串。不幸的是,您将无法使用$.each循环,因为“0”和“1”是单独的成员对象。使用 for 循环iProductIndex

回答by Daniel Protopopov

Data supplied does not allow for your answer, Salman A. See JSON Arraysfor array definition, to have it work your way it must've been defined as

Salman A. 提供的数据不允许您的答案。请参阅JSON Arrays以了解数组定义,要让它按照您的方式工作,它必须被定义为

{"products" : [ {"product_no":"1087",
        "customer":"2",
        "bought_from":"1",
        "date_of_purchase":"2011-04-08",
        "method":"instore",
        "invoice":"0",
        "current":"1"} ] }

To OP: alert(data["0"].product_no); alert(data["1"]["date_of_purchase"]);

对 OP: alert(data["0"].product_no); 警报(数据[“1”][“购买日期”]);

回答by diEcho

try this

试试这个

<script type="text/javascript">
var json_string={
    "logged_in":true,
    "firstname":"Joe",
    "surname":"Bloggs",
    "Full_name":"Joe Bloggs",
    "email":"[email protected]",
    "phone":"+123456789",
    "website":"",
    "age":"26-35",
    "street":"1 Street Ave",
    "city":"Townland",
    "state":"NA",
    "postcode":"1234",
    "country":"Australia",
    "products":2,
    "0":{
        "product_no":"1087",
        "customer":"2",
        "bought_from":"1",
        "date_of_purchase":"2011-04-08",
        "method":"instore",
        "invoice":"0",
        "current":"1"
    },
    "1":{
        "product_no":"24",
        "customer":"2",
        "bought_from":"1",
        "date_of_purchase":"2011-04-08",
        "method":"instore",
        "invoice":"0",
        "current":"1"
    }
};

for (key in json_string) {
// Most modern browsers should have hasOwnProperty by now.
// This keeps us from getting farther up the chain.
if (json_string.hasOwnProperty(key)) {
document.write(key + "->" + json_string[key]);
document.write("<br>");
}
}; 


var pro_1= json_string[0]; // here u change 0 with 1 and get the data of "1"

for (key in pro_1) {
if (pro_1.hasOwnProperty(key)) {
document.write(key + "->" + pro_1[key]);
document.write("<br>");
}
}; 

</script>