3

考虑以下 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 中做到这一点?

4

1 回答 1

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)
    }
}

在此处输入图像描述

如果你添加

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"}] 
于 2013-10-07T10:57:50.653 回答