javascript 使用 jQuery 从 HTML 创建一个 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15691205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a JSON object from HTML using jQuery
提问by Peter
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 from every other box; the same is true for candy types. Furthermore, a candy has additional traits, like color, flavor and quantity.
假设我有一批糖果。货件有许多盒子,每个盒子都有许多独特的糖果类型。每个盒子都有一个唯一的 id,与其他盒子不同;糖果类型也是如此。此外,糖果还有其他特性,如颜色、风味和数量。
Example Code
示例代码
Take the following HTML example:
以以下 HTML 示例为例:
<div class="shipment">
<div class="box" data-boxid="a">
<div class="candy" data-candyid="1" data-color="orange" data-flavor="orange" data-qty="7">
<!-- unimportant content -->
</div>
<div class="candy" data-candyid="2" data-color="red" data-flavor="strawberry" data-qty="4">
<!-- unimportant content -->
</div>
</div>
<div class="box" data-boxid="b">
<div class="candy" data-candyid="3" data-color="green" data-flavor="lime">
<!-- unimportant content -->
</div>
</div>
</div>
Previous Attempts
以前的尝试
I've seen similar examples of table parsing with jQuery's .map()
function, and I've also seen mention of .each()
, but I've been unable to generate any working code.
我见过类似的使用 jQuery.map()
函数解析表的例子,我也见过提到.each()
,但我一直无法生成任何工作代码。
Desired Output
期望输出
I want to generate (with jQuery) a JSON object similarto the following:
我想(使用 jQuery)生成一个类似于以下内容的 JSON 对象:
{
"shipment": {
"a": {
"1": {
"color": "orange",
"flavor": "orange",
"qty": "7"
},
"2": {
"color": "red",
"flavor": "strawberry",
"qty": "4"
}
},
"b": {
"3": {
"color": "green",
"flavor": "lime"
}
}
}
}
Additional Notes
补充笔记
My app already uses jQuery extensively, so it seems like a logical tool for the job.However, if plain 'ol JavaScript is a more appropriate choice, feel free to say so.
我的应用程序已经广泛使用 jQuery,因此它似乎是完成这项工作的合乎逻辑的工具。但是,如果纯 'ol JavaScript 是更合适的选择,请随意说出来。
The HTML is always going to be well-formed and always going to follow a the format specified. However, in some cases, information may be incomplete. Note that the third candy had no quantity specified, so quantity was simply ignored while building the object.
HTML 将始终是格式良好的,并且始终遵循指定的格式。但是,在某些情况下,信息可能不完整。 请注意,第三颗糖果没有指定数量,因此在构建对象时只是忽略了数量。
回答by Blazemonger
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/
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.
如您所见,在每个级别,它都用于.each()
遍历与某个类匹配的元素,然后.find().each()
遍历所需的子元素。在两者之间,.data()
用于获取所需的data-
属性,并且 json 对象是逐级构建的。
回答by Chris
Is this close to what you are looking for? – http://jsfiddle.net/4RPHL/
这是否接近您要找的东西?– http://jsfiddle.net/4RPHL/
I have used data()
and JSON.stringify
to create the json.
我已经使用data()
并JSON.stringify
创建了 json。
Be sure to check your console where I have logged the output.
请务必检查我记录输出的控制台。
$(".candy").each(function() {
console.log(JSON.stringify($(this).data()))
});
回答by Nolo
Nice problem! Thanks to Chris' post I was able to get this to work.
好问题!多亏了 Chris 的帖子,我才能让它发挥作用。
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