You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery从HTML发票数据生成指定格式JSON对象遇问题求助

修正jQuery代码生成目标JSON格式的解决方案

我明白你现在的困扰——当前的代码把每个字段都拆成了独立的小对象,完全没把发票的头部信息和商品项整合到对应的结构里,最终得到的JSON和目标格式相差甚远。还要提一句:你给出的目标JSON示例里有个小问题——同一个对象里不能重复使用items键,正确的写法应该是把多个商品项放到一个items数组里,这样才符合JSON规范。

接下来咱们直接修改代码,实现正确的结构:

var button = $("button");
button.on("click", function() {
  const jsonObj = [];
  // 遍历每一张发票容器
  $('.invoice').each(function() {
    // 初始化当前发票的结构:headers存头部字段,items存商品项数组
    const invoice = {
      headers: {},
      items: []
    };
    // 处理发票头部的所有字段
    $(this).find('.header div').each(function() {
      const fieldKey = $(this).attr('data');
      invoice.headers[fieldKey] = $(this).text();
    });
    // 处理每个商品项
    $(this).find('.item').each(function() {
      const singleItem = {};
      $(this).find('div').each(function() {
        const fieldKey = $(this).attr('data');
        singleItem[fieldKey] = $(this).text();
      });
      invoice.items.push(singleItem);
    });
    // 把组装好的发票结构加入最终数组
    jsonObj.push({ Invoice: invoice });
  });
  console.log(jsonObj);
  console.log(JSON.stringify(jsonObj));
});

代码逻辑说明:

  • 先遍历每个.invoice容器,每张发票对应一个独立的Invoice对象
  • 为每张发票初始化两个核心结构:headers(存储头部键值对的对象)和items(存储所有商品项的数组)
  • 遍历头部的每个字段,将data属性作为键、文本内容作为值,存入headers对象
  • 遍历每个商品项.item,为单个商品创建独立对象,把字段对应存入后,推入items数组
  • 最后把完整的发票结构加入最终的JSON数组

运行后你会得到符合规范的目标JSON结构,类似这样:

[
  {
    "Invoice": {
      "headers": {
        "date": "15-Jan-2020",
        "buyer": "McDonalds",
        "order": "145632"
      },
      "items": [
        { "name": "Big Mac", "quantity": "5", "rate": "20.00" },
        { "name": "Small Mac", "quantity": "10", "rate": "10.00" }
      ]
    }
  }
]

内容的提问来源于stack exchange,提问作者Norman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 11:07:36