Skip to content

Instantly share code, notes, and snippets.

@detj
Last active March 8, 2024 18:17
Show Gist options
  • Save detj/e960773c596bd4f40ff7fb4b4a80367c to your computer and use it in GitHub Desktop.
Save detj/e960773c596bd4f40ff7fb4b4a80367c to your computer and use it in GitHub Desktop.
jq
# Adding a key/value pair to an object based on a condition
#
# Let's say you have a sample object like:
#
# ```json
# {
# "session_id": "some-id-1",
# "timestamp": "some-timestamp",
# "events": [
# {
# "type": "cpu_usage"
# },
# {
# "type": "cpu_usage"
# },
# {
# "type": "cpu_usage"
# },
# {
# "type": "exception",
# "exception": {
# "name": "whatever",
# "exceptions": [],
# "threads": [],
# "device_locale": "something"
# }
# },
# {
# "type": "cpu_usage"
# },
# {
# "type": "cpu_usage"
# }
# ]
# }
# ```
#
# To add {"foo": "bar"} to the "exception" object. do this..
jq '.events |= map(if .type == "exception" then .exception += {"foo": "bar} else . end)' input.json
# To update input.json in-place, with sponge (https://joeyh.name/code/moreutils/)
jq '.events |= map(if .type == "exception" then .exception += {"foo": "bar} else . end)' input.json | sponge input.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment