2013-10-07 60 views
3

考慮以下JSON:如何嵌入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中做到這一點?

+0

如果JSON結構的變化則一世 無法看出如何將其變平的邏輯將是相同的。 – Andy

+0

這不僅僅是扁平化。您還在數組上展開/迭代。如果你的JSON中有多個數組會發生什麼? – user568109

+0

*「有沒有最好的方法?」*你嘗試過什麼? – WiredPrairie

回答

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"}] 
+0

這裏假設OP使用的是Jquery,這個問題中沒有指定,因爲他使用了Node。 – Andy

+0

@安迪編輯。 TNX。 –