Function Reference

->

SQL construct
MySQL equivalent:

Gets a value from JSON by an object key or an array element number and returns it as JSON.

PostgreSQL 17.5
json -> key
json -> index

Parameters

jsonjson | jsonb
Value of the json or jsonb type
keytext
Object key
indexinteger
Array element number starting from 0; a negative one counts from the end

Return value

A json or jsonb value; NULL if the key or element is missing

Examples

Nested object

PostgreSQL 17.5
SELECT '{"user": {"name": "Ann", "tags": ["sql", "pg"]}}'::jsonb->'user' AS user_json;
user_json
{"name":"Ann","tags":["sql","pg"]}

Chain of operators and an element from the end

PostgreSQL 17.5
SELECT '{"user": {"name": "Ann", "tags": ["sql", "pg"]}}'::jsonb->'user'->'tags'->0 AS first_tag,
	'[10, 20, 30]'::jsonb->-1 AS last_element;
first_taglast_element
sql30

Promo code from event data

PostgreSQL 17.5
SELECT event_id,
	event_name,
	metadata->'promo_code' AS promo_code
FROM events
LIMIT 5;
event_idevent_namepromo_code
1app_openSUMMER20
2view_item<NULL>
3app_openNEWYEAR
4view_item<NULL>
5add_to_cartSUMMER20

Details

The result is still JSON, so the operators can be chained: data -> 'user' -> 'tags' -> 0. At the last step, when plain text is needed, use ->>.

If the key is missing, the result is NULL, not an error. A string with JSON must be cast explicitly: '{...}'::jsonb.

See also