将json对象数据转换为json数组数据?

时间:2014-01-02 19:13:50

标签: jquery arrays json object

如何将json对象数据转换为json数组数据?例如,

我在firebug上的控制台上有来自服务器的这个json对象数据,

Object { 0={...}, 1={...}, 2={...}, more...}

json string,

{
    "items": {
        "0": {
            "pub_name": "News",
            "system_id": "57",
            "make_accessible": "0",
            "count": "7",
            "router": "#/post/news/list/"
        },
        "1": {
            "pub_name": "upcoming events",
            "system_id": "134",
            "make_accessible": "0",
            "count": "7",
            "router": null
        }
    },
    "total": 2
}

我需要将其转换为,

[Object { pub_name="Main", system_id="50", make_accessible="0", more...}, Object { pub_name="estate", system_id="122", make_accessible="0", more...}, Object { pub_name="wines", system_id="125", make_accessible="0", more...}, 7 more...]

json string,

{
    "items": [
        {
            "pub_name": "News",
            "system_id": "57",
            "make_accessible": "0",
            "count": "7",
            "router": "#/post/news/list/"
        },
        {
            "pub_name": "upcoming events",
            "system_id": "134",
            "make_accessible": "0",
            "count": "7",
            "router": null
        }
    ],
    "total": 2
}

有可能吗?

1 个答案:

答案 0 :(得分:1)

解决此问题的最佳方法是修复服务器端生成方式,可能是将Items结构转换为您正在使用的服务器端语言的数组。

但是,如果javascript是您唯一的选择,那么您需要做的就是遍历对象键,将它们分配给数组。

var jsonstring = '{\
    "items": {\
        "0": {\
            "pub_name": "News",\
            "system_id": "57",\
            "make_accessible": "0",\
            "count": "7",\
            "router": "#/post/news/list/"\
        },\
        "1": {\
            "pub_name": "upcoming events",\
            "system_id": "134",\
            "make_accessible": "0",\
            "count": "7",\
            "router": null\
        }\
    },\
    "total": 2\
}';

var data = JSON.parse(jsonstring);
console.log(data); // {items: Object, total: 2}

var tempArr = [];
for (key in data.items) {
    tempArr[key] = data.items[key];
}
data.items = tempArr;
console.log(data); // {items: Array[2], total: 2}

http://jsfiddle.net/nje2e/

如果您包含jQuery,则可以使用$.makeArray();

var data = JSON.parse(jsonstring);
console.log(data); // {items: Object, total: 2}
data.items.length = data.total; // adding a length makes it array-like
data.items = $.makeArray(data.items);
console.log(data); // {items: Array[2], total: 2}

http://jsfiddle.net/nje2e/1/