在 JSON 值中带有反勾号的 jq 脚本

jq script with back tick in JSON value

我在 bash 脚本中使用 jq 来解析由 API REST 服务

编辑的 JSON return

这是我的代码(获取.count值)

# getAPIId
# Parse the answer of query API to get the API ID (checking version name)
# return (echo to stdout) the APIID
function getAPIId() {
    local apiId
    local version
    local -i count          

    if [ -z  ]
    then
        echo "Use: getAPIId $apiQuery" >&2
        exit 1
    else    
        # Parse answer to API info
        count=$(echo ""|jq -r '.count')
        if [ "$count" == "0" ]
        then
            echo  >&2
            echo "ERROR: Cannot find an API called ${APINAME}" >&2
            return 1
        else
            for ((i=0; i<count; i++))
            do
                version=$(echo |jq -r '.list['$i'].version')
                if [ "$APIVERSION" == "$version" ] && [ "$APINAME" == "$name" ]
                then
                    apiId=$(echo |jq -r '.list['$i'].id')
                    echo "$apiId"
                    return 0
                fi
            done
        fi
    fi
    return 1

}

这是我尝试解析的 JSON 文件

{"count":1,"next":"","previous":"","list":[{"id":"6d2822e5-a90d-4738-b7b7-ef7d7848cb48","name":"SwaggerPetstore",
"description":"`special key`","context":"/v2","version":"1.0.0","provider":"admin","status":"CREATED","thumbnailUri":null}],"pagination":{"total":1,"offset":0,"limit":25}}

如您所见,字段描述包含反引号值。在这种情况下,jq 失败并且 return 空字符串(因为未找到计数值)

如何避免反引号的问题?

jq 字面值中的反引号完全没有问题。你可以看到如下:

$ jq '.value' <<<'{"otherKey": "`otherValue`", "value": "desired value `with backticks`"}'
"desired value `with backticks`"

不过,关于问题中给出的代码,它过于复杂了。考虑以下替换(根本不需要读取 count,并且只调用 jq 一次),而不是混淆可能出错的地方:

# Aside: Using all-caps names is bad practice. Don't do this.
APINAME=SwaggerPetstore
APIVERSION=1.0.0

getAPIId() {
  [[  ]] || { echo 'Usage: getAPIId "$json"' >&2; return 1; }
  jq -er \
       --arg target_name "$APINAME" \
       --arg target_version "$APIVERSION" '
    .list[] |
    select(.name == $target_name) |
    select(.version == $target_version) |
    .id' <<<""
}

...returns,调用时如下:

s='{
  "count": 1,
  "next": "",
  "previous": "",
  "list": [
    {
      "id": "6d2822e5-a90d-4738-b7b7-ef7d7848cb48",
      "name": "SwaggerPetstore",
      "description": "`special key`",
      "context": "/v2",
      "version": "1.0.0",
      "provider": "admin",
      "status": "CREATED",
      "thumbnailUri": null
    }
  ],
  "pagination": {
    "total": 1,
    "offset": 0,
    "limit": 25
  }
}'

getAPIId "$s"; echo "Exit status is $?" >&2

...正确结果:

6d2822e5-a90d-4738-b7b7-ef7d7848cb48
Exit status is 0

...而如果我们再次 运行 使用无效的名称或版本搜索:

APINAME=NotFound getAPIId "$s"; echo "Exit status is $?" >&2

...正确反映:

Exit status is 4