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

to some thing like below:

{"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}]}
3
  • As the identifier of a property has to be unique and you have Part_Name twice in the "objects", this is not possible. Feb 12, 2014 at 10:38
  • 1
    So go ahead and do it. SO is not a code factory. BTW both are "JSON objects"; your title isn't very descriptive/accurate. Feb 12, 2014 at 10:38
  • JSON.parse() is your friend. Feb 12, 2014 at 10:39

2 Answers 2

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

BTW, your question has nothing to do with JSON. JSON is a format for strings, your snippets are javascript objects. This is quite common mistake, but still a mistake.

0

Without any other libraries (I'm sure someone will use 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]; 
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.