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

如何使用echo输出带转义双引号、可被jq解析的JSON

问题

我想写个函数,用echo输出带反斜杠转义的JSON(比如包含"System.Title": "The \"title\" with double quotes"这种属性),但jq解析输出结果时总是报错。试了各种方法抵消echo对反斜杠的影响,还是没法输出能被jq正常解析的JSON,求成功实现的示例代码。

原测试代码:

jsonWithEscapedCharacters='{
  "fields": {
    "System.AreaPath": "Here\\double-backslah",
    "System.IterationPath": "Ahother\\Double-backslash",
    "System.Title": "The \"title\" with double quotes"
  }
}'

getjsonWithEscapedCharacters() {
  # FAIL echo $jsonWithEscapedCharacters | sed 's/\\/\\\\/g'
  # FAIL echo "$jsonWithEscapedCharacters" | sed 's/\\/\\\\/g'
  # FAIL echo -E "$jsonWithEscapedCharacters" | sed 's/\\/\\\\/g'
  # FAIL echo "$jsonWithEscapedCharacters"
  # FAIL echo -e $jsonWithEscapedCharacters
  echo -e $jsonWithEscapedCharacters
}

echoedJson=$(getjsonWithEscapedCharacters)

titleFromJson=$(jq '.fields["System.Title"]' <<< $jsonWithEscapedCharacters)
title=$(jq '.fields["System.Title"]' <<< $echoedJson)

echo "expected $titleFromJson, actual: $title"
# jsonWithEscapedCharacters is parsed OK but echoedJson cannot be parsed due to jq Parse error
解决方案

问题核心是**echo的转义解析和shell变量引用规则**:

  • 用echo -e会主动解析字符串里的转义序列,把\"变成实际的双引号,导致JSON结构被破坏,jq无法解析
  • 变量引用时没加双引号,会触发shell的分词、通配符扩展,进一步篡改JSON内容

修正只需两步:

  1. 放弃echo -e,用原生echo或echo -E(明确禁用转义解析)
  2. 所有变量引用必须加双引号,避免shell篡改内容

修正后的代码:

jsonWithEscapedCharacters='{
  "fields": {
    "System.AreaPath": "Here\\double-backslah",
    "System.IterationPath": "Ahother\\Double-backslash",
    "System.Title": "The \"title\" with double quotes"
  }
}'

getjsonWithEscapedCharacters() {
  echo "$jsonWithEscapedCharacters"
}

echoedJson=$(getjsonWithEscapedCharacters)

titleFromJson=$(jq '.fields["System.Title"]' <<< "$jsonWithEscapedCharacters")
title=$(jq '.fields["System.Title"]' <<< "$echoedJson")

echo "expected $titleFromJson, actual: $title"

运行后会输出:

expected "The \"title\" with double quotes", actual: "The \"title\" with double quotes"

如果是动态生成这类JSON,更稳妥的方式是直接用jq构建,彻底避免手动处理转义:

# 用jq动态生成带转义的JSON
getDynamicJson() {
  jq -n \
    --arg area "Here\\double-backslash" \
    --arg iteration "Another\\Double-backslash" \
    --arg title 'The "title" with double quotes' \
    '{
      fields: {
        "System.AreaPath": $area,
        "System.IterationPath": $iteration,
        "System.Title": $title
      }
    }'
}

# 直接解析输出结果
getDynamicJson | jq '.fields["System.Title"]'

这种方式下jq会自动处理所有需要转义的字符,绝对不会出现解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:05:48