【问题标题】:Remove mismatch and add missing json jq删除不匹配并添加缺少的 json jq
【发布时间】:2021-02-19 11:47:15
【问题描述】:

您好,我有两个文件,例如:

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是不可能的?

【问题讨论】:

    标签: json shell sed jq


    【解决方案1】:

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

    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
    

    【讨论】:

    • 是的,可以解决所有问题。是否可以泛化而不是写 list_1、list_2 等?或者如果我明确写下我需要更新的所有 json 密钥会更好?
    • @mat656 :是的,你可以,但这完全是一个不同的问题。请为此提出一个新问题
    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 2016-10-21
    • 2022-12-15
    • 1970-01-01
    • 2020-08-23
    • 2013-02-24
    • 1970-01-01
    相关资源
    最近更新 更多