Skip to main content
edited tags
Link
Inian
  • 13.1k
  • 2
  • 42
  • 55
Source Link
Tobias
  • 113
  • 4

Change the value of a key in json while the key is mutable using jq

I have json-files which I wan't to modify. The problem is, that the target-key varies in the json-files. E.g. those two json:

{
    "tasks": [{
        "type": "type1",
        "params": {
            "get": "something",
            "foo": {
                "bar1": ["TEMPLATE"]
            }
        }
    }]
}

{
    "tasks": [{
        "type": "type1",
        "params": {
            "get": "something",
            "foo": {
                "different1": ["TEMPLATE"]
            }
        }
    }]
}

I want to change the value of the keys bar1 and different1 in a dynamical way. The path to the key is constant over all json so with jq it would be:

jq '.tasks[0].params.foo' my_json_file.json

I already tried with the following code:

new_value="something"
jq --arg new "$new_value" '.tasks[0].params.foo[] = $new' my_json_file.json

But with that the value of key bar1 would be "something" instead of ["something"]. To write it out the result would be

{
    "tasks": [{
        "type": "type1",
        "params": {
            "get": "something",
            "foo": {
                "different1": "something"
            }
        }
    }]
}

instead of what I want:

{
    "tasks": [{
        "type": "type1",
        "params": {
            "get": "something",
            "foo": {
                "different1": ["something"]
            }
        }
    }]
}

I'm pretty sure this is not to hard with jq but I cannot find the solution.