3

I am trying to insert a Python(2.7) list of jsonb elements into a Postgresql(9.4) table with a column of datatype: jsonb[].

Here's some code:

import json
anArray = [{"name":"Joe","age":51,"yob":1964,"gender":"male"},{"name":"George","age":41,"dob":1974,"gender":"male"},{"name":"Nick","age":31,"dob":1984,"gender":"male"}]
myArray = []
#here's what I have so far: 
for e in anArray:
    myArray.append(json.dumps(e))
#this gives me
myArray = ['{"name":"Joe","age":51,"yob":1964,"gender":"male"}','{"name":"George","age":41,"dob":1974,"gender":"male"}','{"name":"Nick","age":31,"dob":1984,"gender":"male"}']
#insert commands
insert_sql = "INSERT INTO my_table (data) VALUES (%s);"
insert_data = (myArray, )
cursor.execute(insert_sql, insert_data)

Now when I try to insert myArray, psycopg2 gives me an error

psycopg2.ProgrammingError: column "data" is of type jsonb[] but expression is of type text[]

I'm not quite sure what the correct syntax is to insert this data into the table. Any help/pointers will be appreciated.

Solution Thanks to piro, it was a quick solution.

insert_sql = "INSERT INTO my_table (columns) VALUES (%s::jsonb[]);"
insert_data = (myArray, )
cursor.execute(insert_sql, insert_data)
0

2 Answers 2

7

This is not a psycopg error: it is a PostgreSQL error psycopg is just relying.

The error seems suggesting there is no implicit text[]->jsonb[] cast so you need to add a manual one:

INSERT INTO my_table (columns) VALUES (%s::jsonb[]);
Sign up to request clarification or add additional context in comments.

2 Comments

Well then... That worked like a charm. Thanks so much @piro !
I tried this, but it creates an empty json that cannot be inserted: '''{}''' DETAIL: Array value must start with "{" or dimension information.
6

Use Psycopg JSON adaptation

from psycopg2.extras import Json

data = [
    {"name":"Joe","age":51,"yob":1964,"gender":"male"},
    {"name":"George","age":41,"dob":1974,"gender":"male"},
    {"name":"Nick","age":31,"dob":1984,"gender":"male"}
]

query = '''
    insert into t (j)
    select array_agg(j)
    from jsonb_array_elements(%s) s(j)
'''

cursor.execute(query, (Json(data),))

jsonb_array_elements will return a set of jsonb which will be turned into an array of jsonb by array_agg

1 Comment

This is the best solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.