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

NodeJS从SQLite获取嵌套JSON出现转义格式问题,如何获取规范JSON?

解决SQLite返回嵌套JSON带转义字符的问题

你遇到的问题本质是:SQLite的json_object和json_group_array函数返回的是字符串格式的JSON,而非原生JavaScript对象。当你直接把查询结果传给res.send时,Express会对整个对象做二次JSON序列化,导致原本的JSON字符串被转义成带\"的格式。

这里有两种简单靠谱的解决方法:

方法一:在Node.js中手动解析JSON字符串

修改回调函数,把每个结果项里的order字段用JSON.parse()解析成对象,再返回给前端:

app.get("/api/orders", (req, res, next) => {
  var sql = `SELECT json_object('number', o.number ,'orderType', o.orderType ,'paymentType', o.paymentType ,'isPaid', o.isPaid ,'isReady', o.isReady ,'isProgress', o.isProgress ,'isCanceled', o.isCanceled ,'isDelivered', o.isDelivered ,'createdAt', o.createdAt ,'updatedAt', o.updatedAt ,'orderItems', (SELECT json_group_array(json_object('id', ot.itemID, 'name', ot.itemName, 'quantity', ot.quantity)) FROM orderItems AS ot WHERE ot.orderID = o.number)) AS 'order' FROM orders AS o`;
  db.all(sql, [], function (err, result) {
    if (err) {
      res.status(400).json({"error" : err.message});
      return;
    }
    // 解析每个order字段的JSON字符串,转换成JS对象
    const normalizedOrders = result.map(item => JSON.parse(item.order));
    res.json(normalizedOrders);
  });
});

这样返回的结果就是标准的嵌套JSON结构,不会再有转义字符了。

方法二:调整查询逻辑,在代码中组装嵌套结构(可选)

如果不想依赖SQLite的JSON函数,也可以先查询主订单,再逐个查询对应的订单项,最后在代码里手动组装成嵌套结构:

app.get("/api/orders", (req, res, next) => {
  // 先查询所有主订单数据
  const orderSql = `SELECT number, orderType, paymentType, isPaid, isReady, isProgress, isCanceled, isDelivered, createdAt, updatedAt FROM orders`;
  
  db.all(orderSql, [], async (err, orders) => {
    if (err) {
      return res.status(400).json({"error" : err.message});
    }

    try {
      // 为每个订单查询对应的订单项并组装
      const ordersWithItems = await Promise.all(orders.map(async order => {
        const itemsSql = `SELECT itemID as id, itemName as name, quantity FROM orderItems WHERE orderID = ?`;
        const items = await new Promise((resolve, reject) => {
          db.all(itemsSql, [order.number], (err, rows) => {
            if (err) reject(err);
            else resolve(rows);
          });
        });
        return {...order, orderItems: items};
      }));

      res.json(ordersWithItems);
    } catch (err) {
      res.status(400).json({"error" : err.message});
    }
  });
});

这种方法虽然多了几次数据库查询,但逻辑更直观,也避免了SQL拼接JSON字符串的潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 23:12:46