liveBook · Manning

-> operator

As explained in Just Use Postgres!

The PostgreSQL JSON -> operator extracts a field or array element while preserving the result as JSON.

Use PostgreSQL’s -> operator to navigate JSON objects and arrays while keeping the extracted value in JSON format. Apply it when an application needs selected fields rather than an entire JSON document, such as a pizza’s size, crust, or toppings. section 5.4 section 5.4.1

Keep these behaviors in mind:

  • Write object keys as single-quoted strings: pizza->'size'. The result preserves JSON formatting, so a text value appears with double quotes. section 5.4.1
  • Use ->> when the extracted value must become PostgreSQL text; compare each result using its corresponding representation. section 5.4.1
  • Chain -> operators to descend through nested objects, then use an integer index such as ->0 to extract an array element. section 5.4.1

Extract and filter pizza details

SELECT order_id, order_item_id, pizza->'size' AS pizza_size, pizza->>'crust' AS pizza_crust FROM pizzeria.order_items WHERE order_id = 100 AND pizza->'size' = '\"small\"' AND pizza->>'crust' = 'gluten_free'; The result includes the matching order item with pizza_size shown as \"small\" and pizza_crust shown as gluten_free. Omitting the JSON quotes from the size comparison produces an invalid JSON token error.

Reach nested toppings

SELECT order_id, order_item_id, pizza->'toppings'->'veggies'->0->>'onion' AS onions_amount FROM pizzeria.order_items WHERE order_id = 100; This traverses the toppings object, selects the veggies array’s first element, and converts onion’s value to text. The result is light for the onion pizza and empty for nonmatching items.

Listing 5.3 Chaining the -> operator
SELECT
    order_id, order_item_id,
    pizza->'toppings'->'veggies' as veggies_toppings
FROM pizzeria.order_items
WHERE order_id = 100;

Inspect the complete chained query for retrieving nested vegetable toppings as JSON. section 5.4.1

How Just Use Postgres! covers it

How deep it goes
Explains JSON-versus-text results, comparisons, nested chaining, and array indexing, but does not descend into implementation internals.
Examples
Demonstrates pizza size and crust extraction, filtering, nested vegetable toppings, and selecting an onion value from an array.
What it assumes
Assumes familiarity with SQL SELECT and WHERE clauses while teaching JSON key access, result types, nesting, and arrays.
What you can do after
Apply it via PostgreSQL SQL to extract, traverse, index, and filter JSON fields in order records.
How it connects
Connects the -> operator with the ->> operator, JSON arrays, nested JSON objects, and the @> containment operator.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Just Use Postgres!. The section links point to the parts of the book it draws on.