Conditionally changing JSON values in jq with sub() function

Viewed 1771

I need to alter some values in JSON data, and would like to include it in an already existing shell script. I'm trying to do so using jq, and will need the "sub()" function to cut off a piece of a string value.

Using this command line:

jq '._meta[][].ansible_ssh_pass | sub(" .*" ; "")'

with the data below will correctly replace the value (cutting off anything including the first space in the data), but only prints out the value, not the complete JSON structure.

Here's sample JSON data:

{_meta": {
    "hostvars": {
      "10.1.1.3": {
        "hostname": "core-gw1",
        "ansible_user": "",
        "ansible_ssh_pass": "test123 / ena: test2",
        "configsicherung": "true",
        "os": "ios",
        "managementpaket": ""
      }
    }
}}

Output should be something like this:

{"_meta": {
    "hostvars": {
      "10.1.1.3": {
        "hostname": "core-gw1",
        "ansible_user": "",
        "ansible_ssh_pass": "test123",
        "configsicherung": "true",
        "os": "ios",
        "managementpaket": ""
      }
    }
}}

I assume I have to add some sort of "if... then" based arguments, but haven't been able to get jq to understand me ;) Manual is a bit sketchy and I haven't been able to find any example I could get to match up with what I need to do ...

1 Answers

OK, as usual ... once you post a public question, you then manage to find a solution yourself ... ;)

This jq-call does what I need:

jq '. ._meta.hostvars[].ansible_ssh_pass |= sub(" .*";"" )'
Related