将JSON数据转换为二维数组

时间:2015-09-21 19:44:10

标签: javascript json

JSON数据样本:

 { 
        "GroupA": "Array[37]", 
        "AGroupC": "Array[9]", 
        "GroupB": "Array[12]", 
        "GroupE": "Array[15]", 
        "GroupF": "Array[21]", 
        "GroupD": "Array[6]" 
        }

我有上述数据,我需要将其转换为二维数组但不知道如何操作。任何帮助将不胜感激。 结果应该如下:

["GroupA", "GroupC", "AGroupB", "GroupE", "GroupF", "GroupD"]
[37, 9, 12, 15, 21, 6]

感谢。

3 个答案:

答案 0 :(得分:1)

试试这个:



var dataJson = {
  "GroupA": "Array[37]",
  "AGroupC": "Array[9]",
  "GroupB": "Array[12]",
  "GroupE": "Array[15]",
  "GroupF": "Array[21]",
  "GroupD": "Array[6]"
};

var groupArr = [];
var arrayArr = [];

for (var i in dataJson) {
  if (dataJson.hasOwnProperty(i)) {
    groupArr.push(i);
    arrayArr.push(dataJson[i].match(/\d+/)[0]);
  }
}
alert('groupArr: ' + JSON.stringify(groupArr));
alert('arrayArr: ' + JSON.stringify(arrayArr));




答案 1 :(得分:0)

尝试像这样的事情:

    var dataJson = { 
            "GroupA": "Array[37]", 
            "AGroupC": "Array[9]", 
            "GroupB": "Array[12]", 
            "GroupE": "Array[15]", 
            "GroupF": "Array[21]", 
            "GroupD": "Array[6]" 
            }


    var groupArr = [];
    var arrayArr = [];

    function dataArr() {

        for (i = 0; i < (dataJson.length); i++) {
            groupArr.push(dataJson[i+i]);
            arrayArr.push(dataJson[i+1]);
        }   
    }

//output of each:
//groupArr
// ["GroupA", "GroupC", "AGroupB", "GroupE", "GroupF", "GroupD"]
//arrayArr
// ["Array[37]", "Array[9]", "Array[12]", "Array[15]", "Array[21]", "Array[6]"]

答案 2 :(得分:0)

据我所知,这就是你所要求的。

function convertJSONto2D(json) {
    var 2dArray = [];
    var result  = [];

    2dArray.push(Object.keys(json));

    for(key in json) {
        if (object.hasOwnProperty(key)) {
            result.push(json[key].length);
        }
    }

    2dArray.push(result);

    return 2dArray;
}