json 使用jq检查GitLab-CI中的键是否存在

wfsdck30  于 2023-11-20  发布在  Git
关注(0)|答案(1)|浏览(142)

我试图分析GitLab-CI中的一个变量,看看是否有两个键,以及一个值是否有特定的值。
我现在的样子是这样的:

if [[ $(echo $TRIGGER_PAYLOAD | jq -e '.changes.title.previous and .changes.title.current and .object_attributes.detailed_merge_status == "mergeable"') ]]; then
    echo 'Do something'
fi

字符串
我已经尝试了很多东西,包括select(),但现在我不知道该怎么做。
我只是为此创建了一个最小的例子:

set -x
payload="{\"object_attributes\": {\"detailed_merge_status\": \"draft_status\"},\"changes\": {}}"
echo $(echo $payload | jq -r .)

if jq -e '.changes.title.previous and .changes.title.current and .object_attributes.detailed_merge_status == "mergeable"' <<<"$payload"; then
    echo "true"
else
    echo "false"
fi


这一个工作,反之亦然工作:

set -x
payload="{\"changes\": {\"title\": {\"previous\": \"test\", \"current\": \"test\"}},\"object_attributes\": {\"detailed_merge_status\": \"mergeable\"}}"
echo $(echo $payload | jq -r .)

if jq -e '.changes.title.previous and .changes.title.current and .object_attributes.detailed_merge_status == "mergeable"' <<<"$payload"; then
    echo "true"
else
    echo "false"
fi


如果我现在使用真实的payload而不是虚拟的JSON,它就不能再工作了,而使用jq on .key.key的简单查询可以处理所有值。

$ if jq -e '.changes.title.previous and .changes.title.current and .object_attributes.detailed_merge_status == "mergeable"' <<<"$TRIGGER_PAYLOAD"; then # collapsed multi-line command
++ echo '$ if jq -e '\''.changes.title.previous and .changes.title.current and .object_attributes.detailed_merge_status == "mergeable"'\'' <<<"$TRIGGER_PAYLOAD"; then # collapsed multi-line command'
++ jq -e '.changes.title.previous and .changes.title.current and .object_attributes.detailed_merge_status == "mergeable"'
parse error: Invalid numeric literal at line 2, column 0
++ echo false
false

esbemjvw

esbemjvw1#

当测试命令的返回状态时,您不使用括号测试,而是直接使用命令(*1)。
以下是您可以执行测试的方式:

#!/usr/bin/env bash

# Testing data
triggerPayload='
{
  "changes": {
    "title": {
      "previous": "test",
      "current": "test"
    }
  },
  "object_attributes": {
    "detailed_merge_status": "mergeable"
  }
}
'

# shellcheck disable=SC2016 # Does not expand shell expressions
jqFilter='
$j | (
  .changes.title.previous and
  .changes.title.current and
  .object_attributes.detailed_merge_status == "mergeable"
)'

if jq --exit-status --null-input --argjson j "$triggerPayload" "$jqFilter" >/dev/null; then
    echo 'Do something'
fi

字符串

备注:

  1. [[[实际上是一个shell命令,它接受测试参数,最后一个参数必须分别是]]]

相关问题