用其他文件的内容替换 JSON 散列中的数组元素

Replace array element within JSON hash with content from other file

我有一个配置,其中包含要与来自单独文件的片段交换的内容。我将如何巧妙地实现这一目标?

配置文件可能如下所示:

# config file
{
    "keep": "whatever type of value",
    "manipulate": [
        {
            "foo": "bar",
            "cat": {
                "color": "grey"
            },
            "type": "keep",
            "detail": "keep whole array element"
        },
        {
            "stuff": "obsolete",
            "more_stuff": "obsolete",
            "type": "replace",
            "detail": "replace whole array element with content from separate file"
        },
        {
            "foz": "baz",
            "dog": {
                "color": "brown"
            },
            "type": "keep",
            "detail": "keep whole array element"
        },

    ],
    "also_keep": "whatever type of value"
}

要插入的内容(来自单独的文件)以替换过时的数组元素:

# replacement
{
    "stuff": "i want that",
    "fancy": "very",
    "type": "new"
}

所需的结果应如下所示:

# result
{
    "keep": "whatever kind of value",
    "manipulate": [
        {
            "foo": "bar",
            "cat": {
                "color": "grey"
            },
            "type": "keep",
            "detail": "keep whole array element"
        },
        {
            "stuff": "i want that",
            "fancy": "very",
            "type": "new"
        },
        {
            "foz": "baz",
            "dog": {
                "color": "brown"
            },
            "type": "keep",
            "detail": "keep whole array element"
        },

    ],
    "also_keep": "whatever kind of value",
}

要求:

jq解法:

jq --slurpfile repl repl.json '.manipulate=[.manipulate[] 
     | if .type=="replace" then .=$repl[0] else . end]' config.json
  • repl.json - json 包含替换 JSON 数据的文件

  • --slurpfile repl repl.json - 读取指定文件中的所有 JSON 文本并将已解析的 JSON 值的数组绑定到给定的全局变量

输出:

{
  "keep": "whatever type of value",
  "manipulate": [
    {
      "foo": "bar",
      "cat": {
        "color": "grey"
      },
      "type": "keep",
      "detail": "keep whole array element"
    },
    {
      "stuff": "i want that",
      "fancy": "very",
      "type": "new"
    },
    {
      "foz": "baz",
      "dog": {
        "color": "brown"
      },
      "type": "keep",
      "detail": "keep whole array element"
    }
  ],
  "also_keep": "whatever type of value"
}
jq --slurpfile repl repl.json '.manipulate |= 
  map(if .type=="replace" then $repl[0] else . end)' config.json