2

Consider the following JSON:

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

Now I want to flatten up the JSON so that I get multiple JSON. For the above example the flattened output would be as follows:

{
    "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"
}

And the JSON structure is not fixed it tend to change, but still the flattening has to work the same way. Is there any way to do this in Node.js?

Amol M Kulkarni
  • 21,143
  • 34
  • 120
  • 164

1 Answers1

1

There you go : (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

If you add

console.log(JSON.stringify(t)

you'll get this

    [{"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"}] 
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • This assumes the OP is using Jquery, something not specified in the question because he's using Node. – Andy Oct 07 '13 at 11:04