1

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.

2 Answers 2

1

what about ... ?

jq --arg new "something" '.tasks[0].params.foo[] = [ $new] ' file 
1

You could use with_entries(..) and directly manipulate on the values[] array without accessing the key

jq --arg new "something" '.tasks[0].params.foo |= with_entries(.value[] = $new)'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .