Snelle referentie

PostgreSQL JSON & JSONB spiekbriefje

Snelle referentie voor PostgreSQL JSON en JSONB: extractie-operatoren, insluiting, bestaanscontroles, padwijzigingen en aggregatiefuncties.

· Gepubliceerd

PostgreSQL biedt native ondersteuning voor JSON-gegevens via json (slaat tekst ongewijzigd op) en jsonb (binair formaat met GIN-indexering en snelle zoekopdrachten).

Extractie-operatoren

Enkele pijlen (->, #>) geven json/jsonb terug. Dubbele pijlen (->>, #>>) geven text terug.

SELECT * FROM users WHERE data->>'name' = 'John';
SELECT data->>'name' AS name FROM users;
Operator Linkertype Rechtertype Beschrijving Retourtype
-> jsonb int Array-element ophalen via 0-gebaseerde index jsonb
-> jsonb text Objectveld ophalen op sleutel jsonb
#> jsonb text[] Waarde op het opgegeven pad ophalen jsonb
->> jsonb int Array-element ophalen als tekst text
->> jsonb text Objectveld ophalen als tekst text
#>> jsonb text[] Waarde op pad ophalen als tekst text

Voorbeelden van padquery's

-- Extract nested data.address.city as text
SELECT data#>>'{address,city}' FROM customers;

-- Extract second element in items array
SELECT order_info->'items'->>1 FROM orders;

Booleaanse en insluitingsoperatoren (alleen jsonb)

-- Check if JSON object contains a specific top-level key
SELECT * FROM users WHERE data ? 'email';

-- Check if JSON contains all keys in array
SELECT * FROM users WHERE data ?& array['name', 'email'];

-- Check if JSON contains any key in array
SELECT * FROM users WHERE data ?| array['mobile', 'email'];

-- Containment: Left contains Right
SELECT * FROM users WHERE data @> '{"role": "admin"}'::jsonb;

-- Contained by: Left is contained within Right
SELECT * FROM users WHERE data <@ '{"role": "admin", "active": true}'::jsonb;

JSONB-gegevens wijzigen en bijwerken

Samenvoegen & Sleutels verwijderen

-- Append or update key in jsonb object
UPDATE users SET data = data || '{"active": true}'::jsonb WHERE id = 1;

-- Delete key from object
UPDATE users SET data = data - 'temporary_token' WHERE id = 1;

-- Delete element from array by index
UPDATE users SET tags = tags - 1 WHERE id = 1;

-- Delete nested path
UPDATE users SET data = data #- '{profile,avatar}' WHERE id = 1;

Functie jsonb_set

-- Syntax: jsonb_set(target, path, new_value, create_missing)
UPDATE users
SET data = jsonb_set(data, '{contact,phone}', '"555-0199"', true)
WHERE id = 1;

Aggregatie- & Constructiefuncties

-- Convert rows to JSON array
SELECT json_agg(u) FROM (SELECT id, name FROM users) u;

-- Build JSON object from key-value pairs
SELECT json_build_object('id', id, 'username', name) FROM users;

-- Expand JSON object to table rows
SELECT * FROM json_each('{"a": 1, "b": 2}');
-- Returns columns: key (text), value (json)

Referenties

Verwante onderwerpen