【问题标题】:bash & jq: add attribute with object valuebash & jq:添加带有对象值的属性
【发布时间】:2023-02-08 23:44:41
【问题描述】:

我正在寻找一种解决方案,将具有 JSON 对象值的新属性添加到现有的 JSON 文件中。

我当前的脚本:

if [ ! -f "$src_file" ]; then
  echo "Source file $src_file does not exists"
  exit 1
fi
if [ ! -f "$dst_file" ]; then
  echo "Destination file $dst_file does not exists"
  exit 1
fi

if ! jq '.devDependencies' "$src_file" >/dev/null 2>&1; then
  echo "The key "devDependencies" does not exists into source file $src_file"
  exit 1
fi

dev_dependencies=$(jq '.devDependencies' "$src_file" | xargs )

# Extract data from source file
data=$(cat $src_file)

# Add new key-value
data=$(echo $data | jq --arg key "devDependencies" --arg value "$dev_dependencies" '. + {($key): ($value)}')

# Write data into destination file
echo $data > $dst_file

它正在工作,但是 $dev_dependencies 中的 devDependencies 值被写为字符串:

"devDependencies": "{ @nrwl/esbuild: 15.6.3, @nrwl/eslint-pl[...]"

我怎样才能把它写成原始 JSON ?

【问题讨论】:

标签: json bash jq


【解决方案1】:

我认为您需要 --argjson 选项而不是 --arg。比较

$ jq --arg k '{"foo": "bar"}' -n '{x: $k}'
{
  "x": "{"foo": "bar"}"
}

$ jq --argjson k '{"foo": "bar"}' -n '{x: $k}'
{
  "x": {
    "foo": "bar"
  }
}

【讨论】:

    【解决方案2】:

    --arg 将创建一个细绳多变的。使用--argjson 将值解析为 JSON(可以是对象、数组或数字)。

    来自docs

    --arg name value:

    此选项将值作为预定义变量传递给 jq 程序。 如果你用--arg foo bar运行jq,那么$foo在 程序并具有值"bar"。请注意,value 将被视为 字符串,因此 --arg foo 123 会将 $foo 绑定到 "123"

    命名参数也可用于 jq 程序,如 $ARGS.named

    --argjson name JSON-text:

    此选项将 JSON 编码的值作为 预定义变量。如果你用--argjson foo 123运行jq,那么$foo 在程序中可用,值为123

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 2022-12-17
      相关资源
      最近更新 更多