Skip to content
Latchkey

jq to_entries and from_entries : Object/Pairs

jq to_entries turns an object into an array of {"key":k,"value":v} entries you can map or iterate, and from_entries rebuilds an object from such an array.

APIs that return a map keyed by id force you to iterate values; to_entries gives you both the key and the value per item, and from_entries reassembles the object afterward in CI.

What it does

to_entries converts {"a":1,"b":2} into [{"key":"a","value":1},{"key":"b","value":2}]. from_entries is the inverse, reading entries and taking the key from .key (also .k, .name) and the value from .value (also .v). with_entries(f) is shorthand for to_entries | map(f) | from_entries, letting you transform keys or values in place.

Common usage

Terminal
# iterate an object that is keyed by name
echo '{"web":1,"api":2}' | jq -r 'to_entries[] | "\(.key)=\(.value)"'
# filter keys, then rebuild the object
jq 'to_entries | map(select(.value != null)) | from_entries' obj.json
# the with_entries shorthand
jq 'with_entries(select(.value > 1))' counts.json
# turn a map into a matrix-style array
jq -c 'to_entries | map({name: .key, port: .value})' services.json

Functions

FunctionWhat it does
to_entriesObject to array of {key,value}
from_entriesArray of {key,value} back to object
with_entries(f)to_entries | map(f) | from_entries
.key / .name / .kAccepted key fields for from_entries
.value / .vAccepted value fields for from_entries

Common errors in CI

"jq: error: null (null) has no keys" means to_entries got null from a missing field. "jq: error: Cannot iterate over null (null)" means from_entries (or to_entries[]) received something that was not an array or object. "jq: error: Object keys must be strings" from from_entries means a key value was a number or null; coerce it with tostring.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →