删除不匹配并添加缺少的json jq

垫子656

嗨,我有两个文件,例如:

file1.json

{
  "id": "001",
  "name" : "my_policy",

  "list_1": ["111111111", "22222222","33333333"],
  "list_2": ["a", "b","c"],
  .....
}

然后我有file2.json(并不总是与f1相同的字段)

{    
  "list_1": ["111111111","111111122","33333333"],
  "list_2": ["a", "b","c","d","e"],
  .....
}

我如何通过jq合并两个文件json中的相同键值,并且沉迷于合并操作,从而从file1键中删除file2中不存在的值?所以得到这个结果:

{
 "id": "001",
 "policy" : "my_policy",
 "list_1": ["111111111","111111122","33333333"],
 "list_2": ["a", "b","c","d","e"],
  .....
}
                    

我通过以下方式解决了合并操作:

jq -s 'reduce .[] as $item ({}; reduce ($item | keys_unsorted[]) as $key (.; $item[$key] as $val | ( $val | type) as $ type | .[$key] = if ( $type == "array") then (.[$key] + $val | unique) elif ($type == "object") then (.[$key] + $val) else $val end ))' file1.json f2.json

我该如何解决?还是不可能通过jq?

伊尼安

一旦弄清楚如何找到两个列表项之间的差异并添加/唯一,它们就非常简单。一种方法是

jq --slurpfile s 2.json -f script.jq 1.json

我的脚本内容在哪里

#!/usr/bin/env jq -f

# backup list_1, list_2 from 1.json
.list_1 as $l1  |
.list_2 as $l2  |
# Perform the operation of removing file1 keys not present in 2.json
# for both list_1 and list_2
( ( $l1 - ( $l1 - $s[].list_1 ) ) +  $s[].list_1 | unique ) as $f1 |
( ( $l2 - ( $l2 - $s[].list_2 ) ) +  $s[].list_2 | unique ) as $f2 |
# Update the original result 1.json with the modified content
.list_1 |= $f1 |
.list_2 |= $f2

或直接从命令行

jq --slurpfile s 2.json '
  .list_1 as $l1  |
  .list_2 as $l2  |
  ( ( $l1 - ( $l1 - $s[].list_1 ) ) +  $s[].list_1 | unique ) as $f1 |
  ( ( $l2 - ( $l2 - $s[].list_2 ) ) +  $s[].list_2 | unique ) as $f2 |
  .list_1 |= $f1 |
  .list_2 |= $f2
' 1.json

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章