在Ansible中合并JSON对象数组时复制对象值

xienkqul  于 2023-01-27  发布在  其他
关注(0)|答案(1)|浏览(150)

我正在尝试合并2个JSON文件对象。但是其中2个对象在两个JSON文件中都被附加了相同的值。
在这里,月份和年份值在两个JSON文件中是相同的,比如月份=1和年份=2023,所以它被附加到输出JSON中,我如何避免这种情况?输出中的预期值是月份=1和年份=2023,而不是月份=11和年份=20232023。

投入1

{
    "data": [
        {
            "item_value_01": "APPLICATION",
            "quantity": 1
        },
        {
            "item_value_01": "HERBERT",
            "quantity": 1
        }
    ],
    "month": "1",
    "year": "2023"
}

投入2

{
    "data": [
        {
            "item_value_01": "Test",
            "quantity": 1
        },
        {
            "item_value_01": "Country",
            "quantity": 1
        }
    ],
    "month": "1",
    "year": "2023"
}

错误输出

{
        "data": [
            {
                "item_value_01": "APPLICATION",
                "quantity": 1
            },
            {
                "item_value_01": "HERBERT",
                "quantity": 1
            },
 
            {
                "item_value_01": "Test",
                "quantity": 1
            },
            {
                "item_value_01": "Country",
                "quantity": 1
            }
        ],
        "month": "11",
        "year": "20232023"
    }

预期产出

{
        "data": [
            {
                "item_value_01": "APPLICATION",
                "quantity": 1
            },
            {
                "item_value_01": "HERBERT",
                "quantity": 1
            },
 
            {
                "item_value_01": "Test",
                "quantity": 1
            },
            {
                "item_value_01": "Country",
                "quantity": 1
            }
        ],
        "month": "1",
        "year": "2023"
    }

行动手册

- set_fact:
        list: "{{ list|default({})| 
                    combine({item: input1[item]|default([]) +
                                   input2[item]|default([])}, recursive=true) }}"
     loop: "{{ (input2.keys()|list + input1.keys()|list)|unique }}"
polhcujo

polhcujo1#

在过滤器中设置 * list_merge='append'**合并 *

result: "{{ [input1, input2]|combine(list_merge='append') }}"

给出了预期结果

result:
    data:
    - item_value_01: APPLICATION
      quantity: 1
    - item_value_01: HERBERT
      quantity: 1
    - item_value_01: Test
      quantity: 1
    - item_value_01: Country
      quantity: 1
    month: '1'
    year: '2023'

完整的测试行动手册示例

- hosts: localhost

  vars:

    input1:
      data:
      - item_value_01: APPLICATION
        quantity: 1
      - item_value_01: HERBERT
        quantity: 1
      month: '1'
      year: '2023'

    input2:
      data:
      - item_value_01: Test
        quantity: 1
      - item_value_01: Country
        quantity: 1
      month: '1'
      year: '2023'

    result: "{{ [input1, input2]|combine(list_merge='append') }}"

  tasks:

    - debug:
        var: result

相关问题