Create JSON object
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<div data-color="red" data-type="honda" id="car-div">
</div>
<pre id="print">
</pre>
JavaScript
function constructJson(el, obj) {
numberOfCars = 1;
carColor = el.data('color');
carType = el.data('type');
var jsonObj = new Object();
jsonObj.package = [];
jsonObj.package.push({numberOfCars : numberOfCars});
jsonObj.package.push({Car : [{color:carColor,type:carType}]});
$('#print').text(JSON.stringify(obj,null,2));
}
//-----------------------------------------
$(document).ready(function() {
var cost = 1.1;
var q = 1.1
var price = 1100
var n1 = "Name1";
var n2 = "Name2";
var n3 = "Name3";
var js = new Object();
js.items = [];
js.items.push({sum:price*q*1,name:n1,price:price*1,quantity:q*1});
js.items.push({sum:price*q*2,name:n2,price:price*2,quantity:q*2});
js.items.push({sum:price*q*4,name:n2,price:price*4,quantity:q*4});
js.items.push({sum:price*q*3,name:n1,price:price*1,quantity:q*3});
js.items.push({sum:price*q*5,name:n3,price:price*5,quantity:q*5});
//---------------
try {
//var Cheque = $.parseJSON(js);
var counter = 0;
var goods = [];
for(var i in js.items){
var found = false;
var good = {};
good.price = js.items[i].price/100;
good.name = js.items[i].name;
good.quantity = js.items[i].quantity;
for(var j in goods){
if(goods[j].name==good.name && goods[j].price==good.price){
goods[j].quantity += good.quantity;
found = true;
break;
}
}
if(found){
continue;
}
goods[counter] = good;
counter++;
}
var el = $("#car-div");
constructJson(el, goods);
}
catch (err) {
// Do something about the exception here
alert("Error in JSON string");
}
//var el = $("#car-div");
//constructJson(el, js);
});