Javascript或Ruby。重新格式化JSON对象

时间:2011-04-19 20:16:16

标签: javascript ruby json

我需要打开这个JSON对象:

[
    [
        "email@email.com"
    ],
    [
        "email2@email.com"
    ],
    [
        "email3@email.com"
    ],
    [
        "email4@email.com"
    ]
]

进入这个:

{
    "data": [
        {
            "email": "email@email.com"
        },
        {
            "email": "email2@email.com"
        },
        {
            "email": "email3@email.com"
        },
        {
            "email": "email4@email.com"
        }
] }

这是怎么做到的?

3 个答案:

答案 0 :(得分:1)

嗯,那真的只是一个数组数组,但除此之外。只需遍历数组数组并将相关数据推送到对象中的新数组:

var my_new_object = {};
my_new_object['data'] = [];

for (var i = 0; i < your_array.length; i++) {
  my_new_object.data.push({"email": your_array[i][0]});
}

Working demo

答案 1 :(得分:1)

使用Javascript:

var original = [
[
    "email@email.com"
],
[
    "email2@email.com"
],
[
    "email3@email.com"
],
[
    "email4@email.com"
]
];

var output = {};
output.data = new Array();
for(var i=0;i<original.length;i++){
    var o = new Object();
    o.email = original[i][0];
    output.data.push(o);
}

答案 2 :(得分:0)

你可以在这里测试一下: http://jsfiddle.net/v3fnk/

var data=[["email@email.com"],["email2@email.com"],["email3@email.com"],["email4@email.com"]];

for (var i in data) {
    for (var x in data[i]) {
        $("#info").append(data[i][x] + '<br/>');
    }

}