Last active
March 8, 2024 18:17
-
-
Save detj/e960773c596bd4f40ff7fb4b4a80367c to your computer and use it in GitHub Desktop.
jq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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