2014-02-12 25 views
-2
{"data":[{"Part_Number":"PT_1029"},{"Part_Name":"Real-Time Clock (RTC)"}, 
     {"Quantity_Failed":2},{"Depot_Location":"WarehouseCAL"}, 
     {"Distance_miles":5},{"Quantity_Available":7},{"Unit_Price":75}, 
     {"Delivery_Cost":5.5},{"Applicable_Discount":100}, 
     {"Part_Number":"PT_1030"},{"Part_Name":"Safety Processor"}, 
     {"Quantity_Failed":1},{"Depot_Location":"WarehouseCAL"}, 
     {"Distance_miles":2},{"Quantity_Available":8},{"Unit_Price":85}, 
     {"Delivery_Cost":2.5},{"Applicable_Discount":100}, 
     {"Part_Number":"PT_1036"},{"Part_Name":"Sensors"},{"Quantity_Failed":3}, 
     {"Depot_Location":"WarehouseCAL"},{"Distance_miles":3}, 
     {"Quantity_Available":6},{"Unit_Price":45},{"Delivery_Cost":3.5}, 
     {"Applicable_Discount":100}]} 

一些东西象下面这样:分组对象一起

{"data":[{"Part_Number":"PT_1029","Part_Name":"Real-Time Clock (RTC)", 
      "Quantity_Failed":2,"Depot_Location":"WarehouseCAL","Distance_miles":5, 
      "Quantity_Available":7,"Unit_Price":75,"Delivery_Cost":5.5, 
      "Applicable_Discount":100}, 
     {"Part_Number":"PT_1030","Part_Name":"Safety Processor", 
      "Quantity_Failed":1,"Depot_Location":"WarehouseCAL","Distance_miles":2, 
      "Quantity_Available":8,{"Unit_Price":85,"Delivery_Cost":2.5, 
      "Applicable_Discount":100}, 
     {"Part_Number":"PT_1036","Part_Name":"Sensors", 
      "Quantity_Failed":3,"Depot_Location":"WarehouseCAL", 
      "Distance_miles":3,"Quantity_Available":6,"Unit_Price":45, 
      "Delivery_Cost":3.5,"Applicable_Discount":100}]} 
+0

作为一个属性的标识必须是唯一的,你有'Part_Name'中的“物”的两倍,这是不可能。 – user1983983

+1

所以继续做吧。 SO不是一个代码工厂。 BTW都是“JSON对象”;你的头衔不是很具描述性/准确性。 –

+0

[JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)是你的朋友。 –

回答

2
res = {data:[]} 

obj.data.forEach(function(x) { 
    if(x.Part_Number) 
     res.data.push({}); 
    Object.keys(x).forEach(function(k) { 
     res.data[res.data.length - 1][k] = x[k]; 
    }); 
}); 

顺便说一句,你的问题无关使用JSON。 JSON是字符串的格式,您的片段是JavaScript对象。这是很常见的错误,但仍然是一个错误。

0

没有任何其他库(我敢肯定有人会使用jQuery):

res=[]; 
t={}; 
res.push(t); 
for (var i =0;i<obj.data.length;i++){ 
    var d = obj.data[i]; 
    for (var prop in d){ 
    if (t[prop]){ 
     t={}; 
     res.push(t); 
    } 
    t[prop] = d[prop]; 
    } 
}