Skip to content
Advertisement

How to pass an array of JSON (or JSON array) to pg function to be INSERTed into a Table?

Function to insert rows of json array into a table:

Call this function:

or this form:

or this form:

Always received:

Advertisement

Answer

A JSON array (json) is different from a Postgres array of JSON values (json[]).

vs:

The first is an array nested inside a single JSON value, the second is an array of JSON values.

Postgres array of JSON (json[])

Your (fixed!) function:

Expects a call like this (note all the escaping for the json[] literal):

See:

But a single INSERT with json_populate_record() in a procedure beats looping in a function:

See:

Or simpler with the standard SQL variant in Postgres 14 or later:

See:

Call (!):

db<>fiddle here

JSON array (json)

Typically, you want to pass a JSON array like you tried. So, now with json_populate_recordset():

Or (Postgres 14):

Call (now you can use the value you originally tested with!):

db<>fiddle here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement