Фильтр community.general.json_patch — применение операции JSON Patch (RFC 6902) к объекту
Примечание
Этот плагин фильтра входит в коллекцию community.general (версия 12.6.1).
Возможно, эта коллекция уже установлена, если вы используете пакет ansible. Она не включена в ansible-core. Чтобы проверить, установлена ли она, выполните ansible-galaxy collection list.
Для установки используйте: ansible-galaxy collection install community.general. Для использования этого плагина фильтра могут потребоваться дополнительные компоненты; подробности см. в разделе Требования.
Чтобы использовать его в плейбуке, укажите: community.general.json_patch.
Добавлено в community.general 10.3.0
- Краткое описание
- Требования
- Входные данные
- Позиционные параметры
- Именованные параметры
- Примечания
- См. также
- Примеры
- Возвращаемое значение
Краткое описание
- Этот фильтр применяет одну операцию JSON Patch и возвращает изменённый объект.
- Если операция является проверкой, фильтр возвращает неизменённый объект, если проверка прошла успешно, и значение
noneв противном случае.
Требования
Следующие требования должны быть выполнены на локальном управляющем узле, выполняющем этот фильтр.
- jsonpatch
Входные данные
Описание входных данных фильтра — значения перед | community.general.json_patch.
Параметр | Комментарии |
|---|---|
Входные данные any / обязательный | Список или словарь, представляющий объект JSON, либо строка, содержащая объект JSON. |
Позиционные параметры
Описание позиционных параметров фильтра. В следующем примере это значения positional1, positional2 и так далее: input | community.general.json_patch(positional1, positional2, ...)
Параметр | Комментарии |
|---|---|
op string / обязательный | |
path string / обязательный | Путь JSON Pointer к целевому расположению (см. RFC 6901). |
value any |
Именованные параметры
Описание именованных параметров фильтра. В следующем примере это значения key1=value1, key2=value2 и так далее: input | community.general.json_patch(key1=value1, key2=value2, ...)
Параметр | Комментарии |
|---|---|
fail_test boolean | Если Варианты:
|
from string |
Примечания
Примечание
- При совместном использовании именованных и позиционных параметров позиционные параметры должны указываться перед именованными:
input | community.general.json_patch(positional1, positional2, key1=value1, key2=value2)
См. также
См. также
- RFC 6902
-
Формат обмена данными JavaScript Object Notation (JSON) Patch
- RFC 6901
-
Формат обмена данными JavaScript Object Notation (JSON) Pointer
- Пакет jsonpatch для Python
-
Библиотека Python для применения исправлений JSON
Примеры
- name: Insert a new element into an array at a specified index
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('add', '/1', {'baz': 'qux'}) }}"
vars:
input: ["foo": { "one": 1 }, "bar": { "two": 2 }]
# => [{"foo": {"one": 1}}, {"baz": "qux"}, {"bar": {"two": 2}}]
- name: Insert a new key into a dictionary
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('add', '/bar/baz', 'qux') }}"
vars:
input: { "foo": { "one": 1 }, "bar": { "two": 2 } }
# => {"foo": {"one": 1}, "bar": {"baz": "qux", "two": 2}}
- name: Input is a string
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('add', '/baz', 3) }}"
vars:
input: '{ "foo": { "one": 1 }, "bar": { "two": 2 } }'
# => {"foo": {"one": 1}, "bar": { "two": 2 }, "baz": 3}
- name: Existing key is replaced
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('add', '/bar', 'qux') }}"
vars:
input: { "foo": { "one": 1 }, "bar": { "two": 2 } }
# => {"foo": {"one": 1}, "bar": "qux"}
- name: Escaping tilde as ~0 and slash as ~1 in the path
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('add', '/~0~1', 'qux') }}"
vars:
input: {}
# => {"~/": "qux"}
- name: Add at the end of the array
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('add', '/-', 4) }}"
vars:
input: [1, 2, 3]
# => [1, 2, 3, 4]
- name: Remove a key
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('remove', '/bar') }}"
vars:
input: { "foo": { "one": 1 }, "bar": { "two": 2 } }
# => {"foo": {"one": 1} }
- name: Replace a value
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('replace', '/bar', 2) }}"
vars:
input: { "foo": { "one": 1 }, "bar": { "two": 2 } }
# => {"foo": {"one": 1}, "bar": 2}
- name: Copy a value
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('copy', '/baz', from='/bar') }}"
vars:
input: { "foo": { "one": 1 }, "bar": { "two": 2 } }
# => {"foo": {"one": 1}, "bar": { "two": 2 }, "baz": { "two": 2 }}
- name: Move a value
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('move', '/baz', from='/bar') }}"
vars:
input: { "foo": { "one": 1 }, "bar": { "two": 2 } }
# => {"foo": {"one": 1}, "baz": { "two": 2 }}
- name: Successful test
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('test', '/bar/two', 2) | ternary('OK', 'Failed') }}"
vars:
input: { "foo": { "one": 1 }, "bar": { "two": 2 } }
# => OK
- name: Unuccessful test
ansible.builtin.debug:
msg: "{{ input | community.general.json_patch('test', '/bar/two', 9) | ternary('OK', 'Failed') }}"
vars:
input: { "foo": { "one": 1 }, "bar": { "two": 2 } }
# => Failed
Возвращаемое значение
Ключ | Описание |
|---|---|
Возвращаемое значение any | Изменённый объект или Возвращается: всегда |
Ссылки на коллекцию
© 2012–2018 Michael DeHaan
© 2018–2025 Red Hat, Inc.
Licensed under the GNU General Public License version 3.
https://docs.ansible.com/projects/ansible/latest/collections/community/general/json_patch_filter.html