jq: How to Add a Key to JSON

Updated

Learn how to add a key to a JSON object with jq

jq: How to Add a Key to JSON

Before we start, make sure you have jq installed on your computer. On a Mac, you can install it with Homebrew:

brew install jq

First, open your terminal and navigate to the folder with your JSON file. To add a key, use .key = value:

jq '.role = "admin"' input.json

If the key already exists, it gets overwritten. For numbers or booleans, leave out the double quotes, like .active = true, and for nested keys just chain them: .user.role.

To add several keys at once, merge in an object with . + {"role": "admin", "active": true}. Put the object on the left, {"role": "guest"} + ., and it works as a default that's only used when the key is missing.

To use a shell variable, pass it with --arg (or --argjson for numbers and booleans) instead of pasting it into the filter. For a list of objects, wrap the assignment in map(): jq 'map(.active = true)' input.json.

jq only prints the result. To save it, write to a temp file and move it back:

jq '.role = "admin"' input.json > tmp.json && mv tmp.json input.json
undefined

Never redirect straight into the same file, like > input.json. The shell empties it before jq reads it, and you end up with an empty file.