brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: slurpfile joins two JSON files on a shared id

Json
~/tips/tip-json-slurpfile-join

jq -c --slurpfile u users.json '

Add names from one export to records in another without writing a program.

One export has the orders, another has the users, and the only thing they share is a number. I do not want a database just for that.

With users.json holding [{"id":1,"name":"Anna"},{"id":2,"name":"Bram"}] and orders.json holding [{"user_id":2,"total":12},{"user_id":1,"total":30}]:

jq -c --slurpfile u users.json '
  ($u[0] | INDEX(.id|tostring)) as $by
  | .[]
  | {total, name: $by[.user_id|tostring].name}
' orders.json

The result:

{"total":12,"name":"Bram"}
{"total":30,"name":"Anna"}

--slurpfile u reads the second file into $u. It wraps everything in an array, hence the $u[0]. INDEX builds a lookup object keyed by id, and keys must be strings, which is why both sides go through tostring.

An order whose user is missing still comes out, with "name":null. If you would rather drop those, add select(.name) at the end. If two users share an id, the later one wins without any warning, so check your data when the numbers look odd. Both files are held in memory.

Further reading: jq manual

More Json tips echo '{"id":1,"payload":"{\"user\":\"ann\",\"tags\":[\"x\",\"y\"]}"}' | jq -c '.payload | fromjson | .tags' jq empty config.json Paths() tells you where in a big JSON document a value lives jq -cn --stream 'fromstream(1|truncate_stream(inputs))' big.json const text = '{"createdAt":"2026-11-30T09:00:00Z","name":"x"}'; All Json tips (9) All topics

Link