Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用jQuery从HTML创建JSON对象 问题概述_Javascript_Jquery_Json_Html Parsing_Scrape - Fatal编程技术网

Javascript 使用jQuery从HTML创建JSON对象 问题概述

Javascript 使用jQuery从HTML创建JSON对象 问题概述,javascript,jquery,json,html-parsing,scrape,Javascript,Jquery,Json,Html Parsing,Scrape,假设我有一批糖果。这批货有许多盒子,每个盒子都有许多独特的糖果类型。每个盒子都有一个唯一的id,与其他盒子不同;糖果也是如此。此外,糖果还具有其他特性,如颜色、味道和数量 示例代码 以下面的HTML示例为例: <div class="shipment"> <div class="box" data-boxid="a"> <div class="candy" data-candyid="1" data-color="orange" data-f

假设我有一批糖果。这批货有许多盒子,每个盒子都有许多独特的糖果类型。每个盒子都有一个唯一的id,与其他盒子不同;糖果也是如此。此外,糖果还具有其他特性,如颜色、味道和数量

示例代码 以下面的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>
附加说明 我的应用程序已经广泛使用jQuery,因此它似乎是一个适合这项工作的逻辑工具。但是,如果简单的“ol JavaScript”是一个更合适的选择,请随意这样说


HTML总是格式良好,并且总是遵循指定的格式。然而,在某些情况下,信息可能不完整注意,第三个糖果没有指定数量,因此在构建对象时,数量被忽略。

这与您要查找的接近吗?-

我使用了
data()
JSON.stringify
来创建JSON

确保检查我记录输出的控制台

$(".candy").each(function() {
    console.log(JSON.stringify($(this).data()))
});

这将生成您要求的内容:

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


如您所见,在每个级别上,它都使用
.each()
循环通过与特定类匹配的元素,然后使用
.find().each()
循环通过所需的子级。在这两者之间,
.data()
用于获取所需的
数据-
属性,并且json对象是逐级构建的。

问题很好!多亏了克里斯的帖子,我才得以实现这一点

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

.each()
.find()
组合起来应该可以实现这一点。从顶部开始,按照您的方式处理内部属性。我尝试过类似的方法,但我相信我遇到过处理子对象的子对象(例如,嵌套
.each()
函数)。你能举个例子吗?我不一定要求一个完整的解决方案(毕竟,这是一个虚构的例子)。只是朝着正确的方向迈出了一步。简单而优雅。这似乎是我要找的。如何嵌套
.each()
函数,以便递归地
.stringify
呢?OP指定了所需的输出应该是什么样子,但事实并非如此。Blazemonger:OP使用了关键字“相似”,这很有帮助。但是我仍然不清楚如何实现嵌套结构。太好了,谢谢!另外,我也很感谢对代码的解释。
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