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

JSONPath查询不存在字段时如何返回空串或null以保留正确索引?

你使用的SoftCreatR/JSONPath库原生支持该需求,无需额外复杂处理。

标准JSONPath规范默认会过滤掉不存在目标字段的条目,而该库提供了专属配置项,可以保留原数组索引、并为缺失字段返回自定义默认值,操作方法如下:

  1. 初始化JSONPath实例时,开启allowMissingKeys配置项,同时设置missingKeyDefaultValue为你需要的默认值(空字符串或null均可)
  2. 正常执行JSONPath查询即可得到符合要求的结果

代码示例:

// 解析原始JSON数据
$rawJson = '[
  {"name": "Name1"},
  {"name": "Name2"},
  {"name": "Name3", "surname": "Surname3"}
]';
$originData = json_decode($rawJson, true);

// 初始化JSONPath时配置缺失字段规则
$jsonPath = new \SoftCreatR\JSONPath\JSONPath(
    $originData,
    [
        'allowMissingKeys' => true,
        'missingKeyDefaultValue' => ''
    ]
);

// 执行查询
$queryResult = $jsonPath->find('$[:].surname')->getData();

执行后$queryResult的输出即为:

[
    "",
    "",
    "Surname3"
]

如果你使用的库版本较低,不支持上述两个配置项,可以手动补全索引:

// 先查询所有存在surname字段的取值和对应索引
$existValues = $jsonPath->find('$[?(@.surname)].surname')->getData();
$existIndexes = $jsonPath->find('$[?(@.surname)]~')->getData();

// 生成和原数组长度一致的结果,默认填充空字符串
$queryResult = array_fill(0, count($originData), '');
foreach ($existIndexes as $key => $index) {
    $queryResult[$index] = $existValues[$key];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 22:15:04