2

I have an issue with inserting array of JSONB in postgresql. The issue is related to Issue with Sqlalchemy and inserting array of jsonb to postgresql but there is no answer yet.

Following the indications of http://docs.sqlalchemy.org/en/latest/dialects/postgresql.html#using-json-jsonb-with-array, the column is defined of type :

myKeyOfJsonbArray=db.Column(CastingArray(JSONB)) 

with the class :

class CastingArray(ARRAY):
    def bind_expression(self, bindvalue):
        return cast(bindvalue, self)

I redefine the init function as:

def __init__(self, attributes):
    for key in attributes:
        if key==myKeyOfJsonbArray:
            temp=[]
            for object in attributes[key]:
                temp.append(object)
            print str(temp)
            setattr(self,key,temp)
        else : 
            ...

The print statement prints well the array :
[{u'price_list_id': u'retail', u'value': u'10.0'}]

but psycopg2 returns can't adapt type 'dict' when trying to set the attribute.

a cast temp.append(cast(object,JSONB)) return can't adapt type 'Cast'... I tried tons of solution (eg. with jsonb_build_object) but I can't figured it out. Please if someone already met this problem! Thank you!

EDIT

as the line

psycopg2.extensions.register_adapter(dict, psycopg2.extras.Json)

seemed to did the trick, a more complex dict still cause a problem.

2
  • 1
    CastingArray works fine for me. Can you provide a minimal reproducible example? Commented Jun 29, 2017 at 20:19
  • Hello @univerio, it is a bit difficult to provide a full MCV example, but i will try. Commented Jun 29, 2017 at 21:04

0

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.