Skip to main content
DARKPC.NET

Extract Structured JSON Fields With jq

Filter fictional inventory records with jq and distinguish missing properties from explicit false values.

Difficulty Beginner

Prepare the input

Use jq on Linux. Save the following as devices.json in a practice directory.

[
  {"name": "Display", "available": true, "ports": ["HDMI", "DP"]},
  {"name": "Spare", "available": false, "ports": []},
  {"name": "Unverified"}
]

Select and project fields

jq -r '.[] | select(.available == true) | .name' devices.json
jq '.[] | {name, ports: (.ports // [])}' devices.json
jq '.[] | select(has("available") | not) | .name' devices.json

The first result should be Display. The second keeps the name and substitutes an empty list when ports is null or absent. The third selects Unverified because it lacks the field. Avoid using a default expression indiscriminately for booleans. The // operator treats false and null as absent alternatives.

Troubleshooting and practice

If jq reports that it cannot iterate over a value, run jq type on the file and confirm the root is an array rather than an object. Use jq -e 'type == "array"' devices.json as a shell gate before processing. Add an explicit null availability, then write separate selectors for missing, false and null. Keep values in JSON when passing them to another program. Use text output only when the downstream format can handle its delimiters, and avoid sharing real inventories with unrelated identifiers.

References and related reading