Javascript JSON转换

时间:2014-08-11 02:08:42

标签: javascript json

我有一个像下面这样的JSON(它基本上是用字典构造的):

{ "test1":["a","b","c"], "test2":["c","d"], "test3":["f"] }

我想像上面那样解析和格式化:

[
    {
        "user": "test1",
        "cmd": ["a","b","c"]      
    }
    {
        "user": "test2",
        "cmd": ["c","d"]
    },
    {
        "user": "test3",
        "cmd": ["f"]
    }
]

有关如何使用JavaScript执行此操作的任何建议吗?

2 个答案:

答案 0 :(得分:4)

从您的问题中不清楚您的字典是JS对象还是JSON字符串。如果它是JSON,你必须首先解析它:

var dictionary = JSON.parse(theJSONstring);

然后按照以下说明操作。

如果您支持IE8-,则必须polyfill JSON support


var dictionary = {
    "test1": ["a","b","c"],
    "test2": ["c","d"],
    "test3": ["f"],
};

var commands = Object.keys(dictionary).map(function (key) {
    return { user: key, cmd: dictionary[key] };
});

如果你不幸的是你必须支持古老的浏览器(IE8-),请使用:

var dictionary = {
    "test1":["a","b","c"],
    "test2":["c","d"],
    "test3":["f"],
};

var commands = [];

for (var key in dictionary) {
    if (Object.prototype.hasOwnProperty.call(dictionary, key))
    {
        commands.push({ user: key, cmd: dictionary[key] });
    }
}

答案 1 :(得分:1)

也许是这样的:

var testObject = {
    "test1": ["a", "b", "c"],
        "test2": ["c", "d"],
        "test3": ["f"]
},
userArray = [];

for (test in testObject) {

    if (Object.prototype.hasOwnProperty.call(testObject, test)) {

        userArray.push({
            user: test,
            cmd: testObject[test]
        });

    }
}