将JSON哈希中的数组元素替换为其他文件中的内容

时间:2017-09-14 10:11:39

标签: json edit jq

我有一个配置包含要与单独文件中的代码段交换的内容。我怎么能整齐地实现这个目标呢?

配置文件可能如下所示:

# 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",
}

要求:

  • 内容替换需要根据type密钥的值来完成。
  • 最好使用jq和常用的bash / linux工具。
  • 数组元素排序应保持不变

2 个答案:

答案 0 :(得分:2)

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"
}

答案 1 :(得分:1)

  UIView.animate(withDuration: 0.5, animations: { 
            self.holdingView.alpha = .5
        }, completion: { (complete) in
            if complete {
                self.holdingView.removeFromSuperview()
            }
        })
    }