Pular para o conteúdo principal
eLearner.app
Módulo 15 · Lição 1 de 256/57 no curso~15 min
Lições do módulo (1/2)

Integração JSON e 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;
Exercício#sql.m15.l1.e1
Tentativas: 0Carregando…

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'.

Carregando editor…
Mostrar dica

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

Solução disponível após 3 tentativas

Exercício#sql.m15.l1.e2
Tentativas: 0Carregando…

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'.

Carregando editor…
Mostrar dica

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

Solução disponível após 3 tentativas