ftisiot ideas about food and life
who talks suggestions soft json-pg

How to build a JSON array from a list of elements in PostgreSQL®

Published Jan 9, 2023 by in Postgresql, Json, Jsonb, Elements, Array at https://ftisiot.net/postgresqljson/how-to-build-json-array-from-elements-postgresql/

PostgreSQL® offers two types of data types to handle JSON data, JSON and JSONB, you can use the function json_build_array (jsonb_build_array for JSONB) to create a JSON array from a list of elements.

NOTE: To review the differences between JSON and JSONB check out the related article.

NOTE: more info is available in the PostgreSQL JSON functions documentation page

Create a JSON array from a list of elements with the json_build_array function

You can create a JSON array from a list of elements with the json_build_array (jsonb_build_array for JSONB) function

select 
    jsonb_build_array(1,4,'🍌', 'pizza');

Result

  jsonb_build_array
-----------------------
 [1, 4, "🍌", "pizza"]
(1 row)

NOTE: the array elements can be heterogeneously-typed

Review all the JSON PostgreSQL use-cases listed in the main page


Francesco Tisiot

Mastodon Francesco comes from Verona, Italy and works as a Senior Developer Advocate at Aiven. With his many years of experience as a data analyst, he has stories to tell and advice for data-wranglers everywhere. Francesco loves sharing knowledge with others as a speaker and writer, and is on a mission to defend the world from bad Italian food!

Story logo

© 2023