1

I have a JSON file on a remote server where I want to modify only a single key-value pair and leave the rest untouched. The json has nested values. I want to change one of the nested values.

original json on the remote server:

{
    "foo": {
        "val1": "bar1",
        "val2": "bar2",
    }
}

What I want to save on the remote server:

{
    "foo": {
        "val1": "bar1",
        "val2": "newvalue",
    }
}
Adrian
  • 64
  • 5

1 Answers1

1

Add a new key-value to a json file using Ansible explains how to load the remote json, but this method overwrites the existing nested dictionary, so you end up with this on the remote server:

{
    "foo": {        
        "val2": "newvalue",
    }
}

how to modify multiple values in deep dictionary in ansible explains how to modify key-value pairs, but assumes you already have the json available. It also doesn't explain how to write out the file to the remote location.

Combining both solutions:

- name: load foobar.json
  slurp:
    src: /path/to/foobar.json
  register: imported_json
- debug:
    msg: "{{ imported_json.content|b64decode|from_json }}"

- name: modify individual key-value
  set_fact:
    imported_json: "{{ imported_json.content|b64decode|from_json | combine(item, recursive=True)}}"
  loop:
    - { 'settings': { 'val2': 'newvalue' }}   
- debug:
    var: imported_json.foo.val2

- name: write updated foobar.json to file
  copy: 
    content: "{{ imported_json | to_nice_json }}" 
    dest: /path/to/foobar.json

And I get the result I want on the remote server:

{
    "foo": {
        "val1": "bar1",
        "val2": "newvalue",
    }
}
Adrian
  • 64
  • 5