如何将嵌入式JSON压缩成多个文档

时间:2013-10-07 10:23:09

标签: javascript json node.js

考虑以下JSON:

{
    "Company" : "ABC Company",
    "Place"   : {
                   "Bangalore" :{ 
                                    "Address" : "MG Road",  
                                    "Phone"   : ["988888","888866","365656"]
                                },
                   "Mubmai" :   { 
                                    "Address" : "1st Main Road,West",  
                                    "Phone"   : ["21212","123123","544455"]
                                }
                }
}

现在我想弄平JSON以便获得多个JSON。对于上面的示例,展平输出如下:

{
    "Company" : "ABC Company",
    "Place"   : "Bangalore",
    "Address" : "MG Road",
    "Phone"   : "988888"
},    
{
    "Company" : "ABC Company",
    "Place"   : "Bangalore",
    "Address" : "MG Road",
    "Phone"   : "888866"
},    
{
    "Company" : "ABC Company",
    "Place"   : "Bangalore",
    "Address" : "MG Road",
    "Phone"   : "365656"
},    
{
    "Company" : "ABC Company",
    "Place"   : "Mubmai",
    "Address" : "1st Main Road,West",
    "Phone"   : "21212"
},    
{
    "Company" : "ABC Company",
    "Place"   : "Mubmai",
    "Address" : "1st Main Road,West",
    "Phone"   : "123123"
},    
{
    "Company" : "ABC Company",
    "Place"   : "Mubmai",
    "Address" : "1st Main Road,West",
    "Phone"   : "544455"
}

并且JSON结构没有固定,它往往会改变,但是扁平化仍然必须以相同的方式工作。在Node.js中有没有办法做到这一点?

1 个答案:

答案 0 :(得分:2)

你去:( jsb

var t = [];
for (p in a.Place)
{
    var _=a.Place[p]["Phone"];
    for (i = 0; i < _.length; i++)
    {
        var g = {
                  Company: a.Company,
                  Place: p,
                  Address: a.Place[p]["Address"]
                };
        g.Phone = _[i];
        t.push(g)
    }
}

enter image description here

如果你添加

console.log(JSON.stringify(t)

你会得到这个

    [{"Company":"ABC Company","Place":"Bangalore","Address":"MG Road","Phone":"988888"},{"Company":"ABC Company","Place":"Bangalore","Address":"MG Road","Phone":"888866"},{"Company":"ABC Company","Place":"Bangalore","Address":"MG Road","Phone":"365656"},{"Company":"ABC Company","Place":"Mubmai","Address":"1st Main Road,West","Phone":"21212"},{"Company":"ABC Company","Place":"Mubmai","Address":"1st Main Road,West","Phone":"123123"},{"Company":"ABC 
Company","Place":"Mubmai","Address":"1st Main Road,West","Phone":"544455"}]