JSON
PostgreSQL supports JSON functions and operators which gives flexibility when storing data inside a database column.
PostgreSQL supports two types of JSON columns: JSON
and JSONB
.
The recommended type is JSONB
for almost all cases.
When you use the JSONB
format, the data is parsed when it's put into the database so it's faster when querying and also it can be indexed.
Create a table with a JSON column#
- Go to the Table Editor page in the Dashboard.
- Click New Table and create a table called
books
. - Include a primary key with the following properties:
- Name:
id
- Type:
int8
- Default value:
Automatically generate as indentity
- Name:
- Click Save.
- Click New Column and add 3 columns with the following properties:
- title column
- Name:
title
- Type:
text
- Name:
- author column
- Name:
author
- Type:
text
- Name:
- metadata column
- Name:
metadata
- Type:
jsonb
- Name:
- title column
Insert data into the table#
- Go to the Table Editor page in the Dashboard.
- Select the
books
table in the sidebar. - Click + Insert row and add 5 rows with the following properties:
id | title | author | metadata |
---|---|---|---|
1 | The Poky Little Puppy | Janette Sebring Lowrey | {"ages":[3,6],"price":5.95,"description":"Puppy is slower than other, bigger animals."} |
2 | The Tale of Peter Rabbit | Beatrix Potter | {"ages":[2,5],"price":4.49,"description":"Rabbit eats some vegetables."} |
3 | Tootle | Gertrude Crampton | {"ages":[2,5],"price":3.99,"description":"Little toy train has big dreams."} |
4 | Green Eggs and Ham | Dr. Seuss | {"ages":[4,8],"price":7.49,"description":"Sam has changing food preferences and eats unusually colored food."} |
5 | Harry Potter and the Goblet of Fire | J.K. Rowling | {"ages":[10,99],"price":24.95,"description":"Fourth year of school starts, big drama ensues."} |
View the data#
1select *
2from books;
Query the JSONB
data#
Select the title, description, price, and age range for each book.
1select
2 title,
3 metadata -> 'description' AS description,
4 metadata -> 'price' as price,
5 metadata -> 'ages' -> 0 as low_age,
6 metadata -> 'ages' -> 1 as high_age
7from
8 books;
Note that the ->
operator returns JSONB data. If you want TEXT/STRING data returned, use the ->>
operator.
- metadata -> 'description' (returns a JSON object)
- metadata ->> 'description' (returns STRING/TEXT data)