Skip to content

Instantly share code, notes, and snippets.

@swateek
Last active August 24, 2023 07:55
Show Gist options
  • Save swateek/96f09e620136a6bda6e0637c5a653036 to your computer and use it in GitHub Desktop.
Save swateek/96f09e620136a6bda6e0637c5a653036 to your computer and use it in GitHub Desktop.
working_with_jq.md

jq

  • Print all of the JSON content in a key value pair, like in an environment file.
echo '{"key1":"value1", "key2": "value2", "key3": "value3"}'\
| jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]'

echo '{"key1":"value1", "key2": "value2", "key3": "value3"}'\
| jq -r 'to_entries[] | "\(.key)=\(.value | tostring)"'

# Output
key1=value1
key2=value2
key3=value3
  • Select only few key-values from the JSON contents
echo '{"key1":"value1", "key2": "value2", "key3": "value3"}'\
| jq -r '{key1, key3}'

# Output
{
  "key1": "value1",
  "key3": "value3"
}
  • Select only values of a keys from the JSON contents
echo '{"key1":"value1", "key2": "value2", "key3": "value3"}'\
| jq -r '.key1, .key3' 

# Output
value1
value3

echo '{"key1":"value1", "key2": "value2", "key3": "value3"}'\
| jq '.key1, .key3' 

# Output
"value1"
"value3"
  • Select a few keys from JSON to be printed as key-value pairs
echo '{"key1":"value1", "key2": "value2", "key3": "value3"}'\
| jq -r '["key1", "key3"] as $keys | to_entries[] | select(.key as $k | $keys | contains([$k])) | "\(.key)=\(.value)"'

# do not use multiple jq
echo '{"key1":"value1", "key2": "value2", "key3": "value3"}'\
| jq -r '{key1, key3}' | jq -r 'to_entries[] | "\(.key)=\(.value | tostring)"'

# Output
key1=value1
key3=value3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment