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

如何用Node.js Array.prototype.filter过滤JSON中的指定字符串?

技术解决方案

问题分析

你的代码无法得到预期结果的核心原因有两个:

  1. 过滤逻辑错误:直接将line字段中的完整JSON字符串与字段名"status"做相等比较,显然永远不会匹配。
  2. 数据结构可能不符合预期:如果body是你给出的示例数组,JSON.stringify(body)会把整个数组转成字符串,导致body_W中的line并非单个包含status的JSON对象字符串。

修正后的代码示例

根据你的需求,分两种场景给出解决方案:

场景1:筛选line对应的JSON对象中包含status字段的项

// 假设body是单个包含status的对象(根据你的示例调整)
const body = { status: "waiting" };
const body_W = [{ line: JSON.stringify(body) }];

const result = body_W.filter(checkCha);

function checkCha(item) {
  try {
    // 先将line中的JSON字符串解析为JS对象
    const parsedData = JSON.parse(item.line);
    // 检查对象中是否存在status字段
    return 'status' in parsedData;
  } catch (err) {
    // 处理JSON解析失败的情况,返回false跳过该项
    return false;
  }
}

场景2:筛选line对应的JSON对象中status值为特定内容(如"waiting")的项

const body = { status: "waiting" };
const body_W = [{ line: JSON.stringify(body) }];

const result = body_W.filter(checkCha);

function checkCha(item) {
  try {
    const parsedData = JSON.parse(item.line);
    // 精准匹配status字段的值
    return parsedData.status === "waiting";
  } catch (err) {
    return false;
  }
}

若body本身是示例中的数组结构

如果你的原始数据就是如下数组,无需额外push和stringify,直接对原数组过滤即可:

// 原始示例数组
const body = [
  { line: '{"status":"waiting"}' },
  { line: '{"name":"example"}' }
];

const result = body.filter(checkCha);

function checkCha(item) {
  try {
    const parsedData = JSON.parse(item.line);
    return parsedData.status === "waiting";
  } catch (err) {
    return false;
  }
}

关键注意事项

  • 必须先解析line中的JSON字符串为JavaScript对象,才能对字段进行判断。
  • 加入try-catch捕获JSON解析异常,避免因无效JSON导致程序崩溃。
  • 确认body的实际结构,避免不必要的JSON.stringify操作破坏数据格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 12:18:20