0Pricing
Linux Command Line & Bash Scripting Mastery · Lesson

Transforming and Building JSON Objects with jq

Reshape data with map, to_entries, and object construction to produce new JSON payloads.

Why Transform JSON?

Raw JSON from APIs or log files rarely has the exact shape you need. You might receive a large object but only want specific fields, or you need to rename keys, flatten nested structures, or build a completely new payload to send to another service.

jq is a lightweight, powerful command-line JSON processor that makes these transformations possible in a single pipeline. In this lesson you will learn the three core techniques for reshaping data:

  • Object construction — build a new JSON object from scratch
  • map — apply a transformation to every element of an array
  • to_entries / from_entries — treat an object's key-value pairs as an array so you can filter and rebuild them

All examples assume jq is installed (apt install jq / brew install jq).

Object Construction Basics

The most fundamental jq feature is object construction: wrapping expressions in {} to build a new JSON object. You choose which fields to include and what to call them.

Syntax:

  • { newKey: .existingField } — rename a field
  • { name, age } — shorthand when the new key matches the field name
  • { total: (.price * .qty) } — compute a value inline

The snippet below reads a product JSON and produces a leaner shape with a computed subtotal field.

#!/usr/bin/env bash
# Object construction: pick and rename fields
product='{
  "id": 42,
  "name": "Widget Pro",
  "price": 9.99,
  "qty": 3,
  "warehouse": "EU-West"
}'

echo "$product" | jq '{
  productId: .id,
  name,
  subtotal: (.price * .qty)
}'

All lessons in this course

  1. Filtering and Selecting JSON with jq Pipelines
  2. Transforming and Building JSON Objects with jq
  3. Consuming REST APIs with curl and jq Together
  4. Editing YAML Configuration Files with yq
← Back to Linux Command Line & Bash Scripting Mastery