0

我有一个 json 文件 sample.json。下面是来自 sample.json 的片段 -

{
"AddOnModules": {
        "Description": "add on modules",
        "Type": "Array",
        "AllowedValues": [
            "a",
            "b",
            "c"
        ],
        "value": []
    }
}

我试图在运行管道时通过 git ci 变量(参数值)为 AddOnModules 提供值。以下是管道的片段 -

stages: 
  - deploy
  
# Job to deploy for development  
dev-deploy:

  variables:

  before_script:
    - apk add jq
    
  image: python:3.7.4-alpine3.9
  script:
    - tmp=$(mktemp)
    - jq -r --arg add_on_modules "$add_on_modules" '.AddOnModules.value  |= .+ [$add_on_modules] ' sample.json > "$tmp" && mv "$tmp" sample.json
    - cat sample.json
  stage: deploy
  tags: 
    - docker
    - linux
  only:
    variables:
        - $stage =~ /^deploy$/ && $deployment_mode =~ /^dev$/

在运行管道时,我通过 git ci 将变量 add_on_modules 的值指定为“a”、“b”。在执行 cat sample.json 时,观察到 -

{
    "AddOnModules": {
            "Description": "add on modules",
            "Type": "Array",
            "AllowedValues": [
                "a",
                "b",
                "c"
            ],
            "value": [ "\"a\",\"b\""]
        }
 }

额外的双引号被前置和附加,而现有的双引号被转义。我想要输出类似 -

{
        "AddOnModules": {
                "Description": "add on modules",
                "Type": "Array",
                "AllowedValues": [
                    "a",
                    "b",
                    "c"
                ],
                "value": ["a","b"]
            }
}

看起来我缺少 jq 的东西 -

- jq -r --arg add_on_modules "$add_on_modules" '.AddOnModules.value  |= .+ [$add_on_modules] ' sample.json > "$tmp" && mv "$tmp" sample.json

尝试使用带有 jq 的 -r/--raw-output 标志但没有成功。关于如何解决这个问题的任何建议?

这就是我运行管道的方式 -

管道运行

4

1 回答 1

0

如果 $add_on_modules 是["a","b"]

如果您可以将 add_on_modules 设置为 JSON 数组的文本表示,那么您将使用--argjson,如下所示:

add_on_modules='["a","b"]'
jq -r --argjson add_on_modules "$add_on_modules" '
 .AddOnModules.value  += $add_on_modules
' sample.json

如果 $add_on_modules 是字符串"a","b"

add_on_modules='"a","b"'
jq -r --arg add_on_modules "$add_on_modules" '
  .AddOnModules.value  += ($add_on_modules|split(",")|map(fromjson)) 
  ' sample.json
于 2020-10-27T20:49:45.463 回答