json - 使用 JQ 将一个 JSON 文件值更新为另一个 JSON 文件值(在所有级别)

标签 json merge jq

我有两个 JSON 文件:

source.json:

{
  "general": {
    "level1": {
      "key1": "x-x-x-x-x-x-x-x",
      "key3": "z-z-z-z-z-z-z-z",
      "key4": "w-w-w-w-w-w-w-w"
    },
    "another" : {
      "key": "123456",
      "comments": {
        "one": "111",
        "other": "222"
      }
    }
  },
  "title": "The best"
}

target.json:

{
  "general": {
    "level1": {
      "key1": "xxxxxxxx",
      "key2": "yyyyyyyy",
      "key3": "zzzzzzzz"
    },
    "onemore": {
      "kkeeyy": "0000000"
    }
  },
  "specific": {
    "stuff": "test"
  },
  "title": {
    "one": "one title",
    "other": "other title"
  }
}

考虑到所有级别,我需要两个文件中存在的键的所有值,从 source.json 复制到 target.json
我已经看到并测试了 this post 的解决方案。 它只复制第一级 key ,我无法让它执行我需要的操作。 this post 中的解决方案的结果如下所示:

{
  "general": {
    "level1": {
      "key1": "x-x-x-x-x-x-x-x",
      "key3": "z-z-z-z-z-z-z-z",
      "key4": "w-w-w-w-w-w-w-w"
    },
    "another": {
      "key": "123456",
      "comments": {
        "one": "111",
        "other": "222"
      }
    }
  },
  "specific": {
    "stuff": "test"
  },
  "title": "The best"
}

“常规”键下的所有内容均按原样复制。
我需要的是这样的:

{
  "general": {
    "level1": {
      "key1": "x-x-x-x-x-x-x-x",
      "key2": "yyyyyyyy",
      "key3": "z-z-z-z-z-z-z-z"
    },
    "onemore": {
      "kkeeyy": "0000000"
    }
  },
  "specific": {
    "stuff": "test"
  },
  "title": {
    "one": "one title",
    "other": "other title"
  }
}

仅应复制“key1”和“key3”。
不得删除目标 JSON 中的键,并且不应创建新键。

有人可以帮忙吗?

最佳答案

您可以采取的一种方法是获取每个输入的所有标量值的所有路径并采用设置的交集。然后从这些路径将值从源复制到目标。

首先,我们需要一个相交函数(制作起来非常困难):

def set_intersect($other):
    (map({ ($other[] | tojson): true }) | add) as $o
    | reduce (.[] | tojson) as $v ({}; if $o[$v] then .[$v] = true else . end)
    | keys_unsorted
    | map(fromjson);

然后进行更新:

$ jq --argfile s source.json '
reduce ([paths(scalars)] | set_intersect([$s | paths(scalars)])[]) as $p (.;
    setpath($p; $s | getpath($p))
)
' target.json

关于json - 使用 JQ 将一个 JSON 文件值更新为另一个 JSON 文件值(在所有级别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52853997/

相关文章:

javascript - 访问 API 返回 JSON 数组

php - 内容类型不随 CURLOPT_HTTPHEADERS 改变

ruby-on-rails - 哈希 to_json : how can I skip the key and list only the values in the JSON response?

合并排序的 C 实现,如 Cormen's et al "Introduction to algortithms"not working properly 所示

json - 如何使用 jq 将多个 json 对象与分隔符逗号连接起来

docker - 如何在 docker 中使用 httpie 和 jq?

json - 显示 JSON 数组数据时出错 - 无法将复杂对象类型转换为简单值

Git rebase 或 merge

javascript - ImmutableJS 记录合并

json - 在 bash 中将无效的 json 转换为有效的