跳转到主要内容
eLearner.app
模块 15 · 第 1 课(共 2)课程中的56/57~15 min
模块课程(1/2)

JSON 和 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;
锻炼#sql.m15.l1.e1
尝试:0加载中...

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

正在加载编辑器...
显示提示

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

3 次尝试后可用的解决方案

锻炼#sql.m15.l1.e2
尝试:0加载中...

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

正在加载编辑器...
显示提示

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

3 次尝试后可用的解决方案