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

How to create a JSON object from keys and values arrays in PostgreSQL®?

Published Jan 9, 2023 by in Postgresql, Json, Jsonb, Create, Array, Key, Value at https://ftisiot.net/postgresqljson/howto-create-json-from-keys-and-values-arrays-postgresql/

PostgreSQL® offers two types of data types to handle JSON data, JSON and JSONB, you can use the function json_object (jsonb_object for JSONB) to create a JSON object from two arrays of keys and values.

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 object from two arrays of keys and values with the json_object function

You can create a JSON object from two arrays (one of keys and one of values) with the json_object (jsonb_object for JSONB) function

select 
    jsonb_object(
        ARRAY['name', 'pizza'], 
        ARRAY['Francesco', 'Margherita']);

Result

                 jsonb_object
----------------------------------------------
 {"name": "Francesco", "pizza": "Margherita"}
(1 row)

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