Salt la conținutul principal
eLearner.app
Modulul 15 · Lecția 1 din 256/57 în curs~15 min
Lecții din modul (1/2)

Integrare JSON și JSONB

JSON and JSONB Integration

PostgreSQL rewrote the rules of databases by combining the reassuring, rock-solid ACID nature of SQL with the dynamic, fluid flexibility typical of NoSQL. It did so by offering columns natively dedicated to storing JSON data.

Heads up: in Postgres it's almost always recommended to use JSONB. The "B" stands for Binary: JSON documents stored in these columns lose their purely textual formatting, but they gain the ability to be validated, queried with very high performance, manipulated, and even indexed with the classic B-tree or GIN INDEX.

Navigating JSON: the "Arrow" operator

Unfortunately the ecommerce database currently has no predefined pure JSON columns. We can, however, create temporary JSON values and "cast" them from text!

When working with JSON, the operators that drill into objects and arrays are -> (keeps the data in its pure jsonb/json form) or its "extended" version ->> (converts the encountered JSON data to text).

Academic example, as if a "metadata" JSON column existed:

SQL
-- Look up the value associated with the info key
SELECT metadata->'info' FROM users;

-- Drill into info, and grab city as text
SELECT metadata->'info'->>'city' FROM users;
Exercițiu#sql.m15.l1.e1
Încercări: 0Se încarcă…

Let's query JSON on the fly. Project this json literal `'{"user": {"name": "Mario"}}'::json` and use the `->` operator combined with the textual version (`->>`) to extract 'name', naming the extracted column 'user_name'.

Se încarcă editorul...
Afișează indiciu

Cast to ::json or ::jsonb, and use ->'user'->>'name'.

Soluție disponibilă după 3 încercări

Exercițiu#sql.m15.l1.e2
Încercări: 0Se încarcă…

What if we pass an array? Array access in json_b in Postgres works by INDEX (zero-based). Extract the SECOND element as text from `'["A", "B", "C"]'::json` and name it 'letter'.

Se încarcă editorul...
Afișează indiciu

->>1 (it's zero-based!)

Soluție disponibilă după 3 încercări