Create A JSON Object From HTML Using JQuery
Problem Overview Let's say I have a shipment of candy. The shipment has a number of boxes, and each box has a number of unique candy types. Every box has a unique id, different f
Solution 1:
This generates what you asked for:
var json = {};
$('.shipment').each(function(i,a) {
json.shipment = {};
$(a).find('.box').each(function(j,b) {
var boxid = $(b).data('boxid');
json.shipment[boxid] = {};
$(b).find('.candy').each(function(k,c) {
var $c = $(c),
candyid = $c.data('candyid'),
color = $c.data('color'),
flavor = $c.data('flavor'),
qty = $c.data('qty');
json.shipment[boxid][candyid] = {};
if (color) json.shipment[boxid][candyid].color = color;
if (flavor) json.shipment[boxid][candyid].flavor = flavor;
if (qty) json.shipment[boxid][candyid].qty = qty;
});
});
});
http://jsfiddle.net/mblase75/D22mD/
As you can see, at each level it uses .each()
to loop through the elements matching a certain class and then .find().each()
to loop through the desired children. In between, .data()
is used to grab the desired data-
attributes and the json object is built level by level.
Solution 2:
Is this close to what you are looking for? – http://jsfiddle.net/4RPHL/
I have used data()
and JSON.stringify
to create the json.
Be sure to check your console where I have logged the output.
$(".candy").each(function() {
console.log(JSON.stringify($(this).data()))
});
Solution 3:
Nice problem! Thanks to Chris' post I was able to get this to work.
var shipments = [],
shipment = {},
boxes = {},
candy = {};
$(".shipment").each(function() {
var shipment = {},
boxes = {};
$(this).children().each(function(){
var boxdata = $(this).data();
candy = {};
$(this).children().each(function(){
var candydata = $(this).data();
candy[candydata["candyid"]] = {
color: candydata["color"],
flavor: candydata["flavor"],
qty: candydata["qty"]
};
boxes[boxdata["boxid"]] = candy;
});
//console.log(JSON.stringify(boxes)); // works
});
shipment = {shipment: boxes};
shipments.push(shipment); // for multiples
});
console.log(JSON.stringify(shipments[0]));
console.log(shipments.length); // 1 for the example html above
Post a Comment for "Create A JSON Object From HTML Using JQuery"