2012-11-08 80 views
0

我有以下的JSON如何更改JSON格式?

{"result": { "a": 1, "b": 2 "c": [ { "d": 3, "e": 4 }, { "d": 3, "e": 4 } ] }}

我想改变它变成了这个样子:

{"result": [{ "a": 1, "b": 2, "d": 3, "e": 4 }, { "a": 1, "b": 2, "d": 3, "e": 4 }]}

有没有办法改变的JSON这样吗?

+0

您可以发布您当前的代码? – elclanrs

+1

不要更改json字符串,更改基础对象。 –

+0

当然,您可以使用文本编辑器并根据自己的喜好进行更改。但是,如果你想以编程的方式做到这一点,你最好将JSON读入数据结构并改变结构。 –

回答

3

您可以使用此Array.prototype.reduce()

var obj = {"result": { "a": 1, "b": 2, "c": [ { "d": 3, "e": 4 }, { "d": 3, "e": 4 } ] }}; 

var res = obj.result.c.reduce(function(res, arrObj) { 
    res.result.push({a:obj.result.a, b:obj.result.b, d:arrObj.d, e:arrObj.e}); 
    return res; 
}, {result:[]}); 

,还是应更动态的,那么这样的:

var res = obj.result.c.reduce(function(res, arrObj) { 
    Object.keys(obj.result).forEach(function(key) { 
     if (typeof obj.result[key] !== 'object') 
      arrObj[key] = obj.result[key]; 
    }); 
    res.result.push(arrObj); 
    return res; 
}, {result:[]});