- 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