如何使用jquery将json数组解析为javascript数组?

时间:2015-12-07 03:47:14

标签: jquery arrays json

以下是网址中的JSON数组:http://ins.mtroyal.ca/~nkhemka/2511/process.php

{"Roll":[{"value":3},{"value":5},{"value":2},{"value":6},{"value":2}]}

我正在尝试将此数组解析为JavaScript数组,例如

var diceList = [3, 5, 2, 6, 2 ]

因此,我有:

$.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php")
    .done(function (data){
        diceList = $.parseJSON(data);
        alert(diceList);
});

执行代码时,警报只会显示[object Object]。我不确定如何做到这一点!

4 个答案:

答案 0 :(得分:3)

尝试使用map()方法获取格式化结果,alert()函数可以显示字符串值,这样您就可以将数组从join(',')函数更改为字符串

$.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php")
    .done(function (data){
        diceList = $.parseJSON(data);
        var list = $.map(diceList.Roll, function(v){
          return v.value;
        })   
        alert(list.join(','));
});

答案 1 :(得分:0)

    $.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php")
    .done(function (data){
        var diceList= new Array(data.Roll.length);
        for( var i= 0; i< data.Roll.length; i++){
            diceList[i]=data.Roll[i].value;
        }
        alert(diceList);
    });

答案 2 :(得分:0)

使用下划线非常容易:

data = JSON.parse(data);
diceList = [];
for (var i in data.Roll)
    diceList.push( data.Roll[i].value );
console.log(diceList);

arr = [0,0,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1]

https://jsfiddle.net/rabztbcd/

答案 3 :(得分:0)

迭代滚动项目以将其值放入数组中。

JsFiddle

$.post("http://ins.mtroyal.ca/~nkhemka/2511/process.php")
    .done(function (data) {
        var diceList = $.parseJSON(data);
        var array = [];

        $.each( diceList.Roll, function(i, item) {

            array.push(item.value);
        });

        alert(array);
});