jq replace json value if key exists

2020-07-20

jq replace json value if key exists

Let say you have a dataset with json objects:

names.json

{"id": 1, "name": "Arthur", "age": "21"}
{"id": 2, "name": "Richard", "age": "32"}
{"id": 3, "age": "33"}

then

jq 'if .name? then .name="X" else . end' -c names.json

will produce:

{"id": 1, "name": "X", "age": "21"}
{"id": 2, "name": "X", "age": "32"}
{"id": 3, "age":"33"}
Snippetsjqoneliner

Grep non-greedy match

Ubuntu prevent updating of a specific package