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#

  1. Go to the Table Editor page in the Dashboard.
  2. Click New Table and create a table called books.
  3. Include a primary key with the following properties:
    • Name: id
    • Type: int8
    • Default value: Automatically generate as indentity
  4. Click Save.
  5. Click New Column and add 3 columns with the following properties:
    • title column
      • Name: title
      • Type: text
    • author column
      • Name: author
      • Type: text
    • metadata column
      • Name: metadata
      • Type: jsonb

Insert data into the table#

  1. Go to the Table Editor page in the Dashboard.
  2. Select the books table in the sidebar.
  3. Click + Insert row and add 5 rows with the following properties:
idtitleauthormetadata
1The Poky Little PuppyJanette Sebring Lowrey{"ages":[3,6],"price":5.95,"description":"Puppy is slower than other, bigger animals."}
2The Tale of Peter RabbitBeatrix Potter{"ages":[2,5],"price":4.49,"description":"Rabbit eats some vegetables."}
3TootleGertrude Crampton{"ages":[2,5],"price":3.99,"description":"Little toy train has big dreams."}
4Green Eggs and HamDr. Seuss{"ages":[4,8],"price":7.49,"description":"Sam has changing food preferences and eats unusually colored food."}
5Harry Potter and the Goblet of FireJ.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)

Resources#