← 中文资源

简体中文版本

JSONPath 子集查询引擎

实现点分路径、数字下标与星号通配的 JSONPath 子集,返回标量或匹配数组。

阅读英文原文

目标

实现支持 $.a.b 点分段、[0] 数字下标、[*] 通配展开的 JSONPath 子集。对每个路径求值输出解析结果:通配返回全部匹配的数组,单命中返回标量本身。

要点

先把路径切分为 key 与 idx 令牌;求值维护候选节点前沿,key 步取属性、idx 步取数组元素、星号把数组节点展开为全部元素。前沿恰一个节点返回标量,否则返回匹配数组。

提示

把 [*] 当普通下标只返回首个元素;单元素通配直接返回裸标量会误报结果形态。

验证

运行两个样例:缺失键返回空数组而非 null;混合星号与下标的路径要跳过缺失字段的项。 公开样例(与参考实现实测一致):

  • 输入 {"data":{"a":{"b":[{"c":1},{"c":2}]},"items":[{"name":"x"},{"name":"y"}]},"paths":["$.a.b[1].c","$.items[*].name","$.missing"]},期望 {"results":[2,["x","y"],[]]}。
  • 输入 {"data":{"config":{"retries":3}},"paths":["$.config.retries"]},期望 {"results":[3]}。

代码示例

function tokenize(path) {
  const parts = [];
  let rest = path.slice(1);
  while (rest.length > 0) {
    if (rest.startsWith('[')) {
      const end = rest.indexOf(']');
      parts.push({ idx: rest.slice(1, end) });
      rest = rest.slice(end + 1);
    } else if (rest.startsWith('.')) {
      rest = rest.slice(1);
    } else {
      const m = rest.match(/^([^.\[]+)/);
      parts.push({ key: m[1] });
      rest = rest.slice(m[1].length);
    }
  }
  return parts;
}

function query(root, path) {
  let current = [root];
  for (const part of tokenize(path)) {
    const next = [];
    for (const node of current) {
      if (part.idx !== undefined) {
        if (part.idx === '*') {
          if (Array.isArray(node)) next.push(...node);
        } else {
          const v = node == null ? undefined : node[Number(part.idx)];
          if (v !== undefined) next.push(v);
        }
      } else {
        const v = node == null ? undefined : node[part.key];
        if (v !== undefined) next.push(v);
      }
    }
    current = next;
  }
  if (current.length === 1) return current[0];
  return current;
}

const payload = JSON.parse(input);
console.log(JSON.stringify({ results: payload.paths.map((p) => query(payload.data, p)) }));