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

使用jq命令遍历含空格值的JSON数组时遇解析错误的技术求助

解决含空格的JSON数组元素遍历与验证问题

问题背景

我们需要处理project.json中的replacements数组:

  • 部分对象的filename字段值包含空格
  • 需验证两个规则:
    1. replaceWith字段值必须以SFP_或SECURE_开头
    2. 数组内的对象不能包含allowUnsetEnvVariable字段

当前使用的bash脚本通过for循环遍历jq输出的元素时,因bash默认按空格分词,导致带空格的JSON对象被拆分成多个片段,触发jq解析错误。

解决方案

方案1:用jq直接完成全部验证(推荐)

无需bash遍历,直接用jq处理JSON并完成规则校验,更高效且避免分词问题:

filename="project.json"
if [[ ! -f "$filename" || ! -s "$filename" ]]; then exit 1; fi

# 执行验证并输出错误信息
jq -r '
.replacements[] | 
(
  if .replaceWith | test("^(SFP_|SECURE_)") | not then
    "错误:replaceWith字段不符合要求 - " + (. | tostring)
  elif has("allowUnsetEnvVariable") then
    "错误:对象包含禁止的allowUnsetEnvVariable字段 - " + (. | tostring)
  else
    empty
  end
)
' "$filename"

# 根据jq输出判断是否有错误
if [ -n "$(jq -r '.replacements[] | (if .replaceWith | test("^(SFP_|SECURE_)") | not or has("allowUnsetEnvVariable") then 1 else empty end)' "$filename")" ]; then
  exit 1
fi

说明:

  • test("^(SFP_|SECURE_)")验证replaceWith的开头规则
  • has("allowUnsetEnvVariable")检查是否包含禁止字段
  • 脚本会输出所有不符合规则的对象,并在最后返回非0状态码表示验证失败

方案2:修复bash遍历的分词问题

如果必须用bash逐个处理数组元素,可通过while read配合正确的IFS设置来避免空格拆分:

filename="project.json"
if [[ ! -f "$filename" || ! -s "$filename" ]]; then exit 1; fi

# 使用while read读取jq的每行输出(每行一个完整JSON对象)
# 设置IFS为空避免换行被截断,-r禁止转义
while IFS= read -r item; do
  echo "当前处理对象:$item"

  # 验证replaceWith开头规则
  replaceWith=$(echo "$item" | jq -r '.replaceWith')
  if [[ ! "$replaceWith" =~ ^(SFP_|SECURE_) ]]; then
    echo "错误:replaceWith字段不符合要求 - $replaceWith"
    exit 1
  fi

  # 检查是否包含allowUnsetEnvVariable字段
  has_forbidden=$(echo "$item" | jq -r 'has("allowUnsetEnvVariable")')
  if [[ "$has_forbidden" == "true" ]]; then
    echo "错误:对象包含禁止的allowUnsetEnvVariable字段"
    exit 1
  fi

done < <(jq -c '.replacements[]' "$filename")

说明:

  • < <(jq -c '.replacements[]' "$filename")将jq的输出作为while read的输入,每行是一个完整的JSON对象
  • IFS=和read -r确保包含空格的JSON对象不会被拆分,完整读取每行内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:45:09