Skip to content

How to insert array of json? #1466

Answered by dvarrazzo
raw1248 asked this question in Q&A
Discussion options

You must be logged in to vote

Looking at mogrify:

>>> print(cur.mogrify("%(data)s", insertdata).decode())
ARRAY['{"foo": 1}','{"foo": 2}']

The adapter for the json wrapper doesn't add a cast to the snippet it generates, so it's passed as "unknown" to the parser. Postgres can cast unknown -> json, but, because there isn't a type such as "unknown array" (there is "anyarray", but it's only a pseudotype to be used as parameter type, I don't think it can be really instantiated), the array is temporarily converted to a text array. Because there isn't an implicit text[] -> json[] cast, automatic cast fails.

You can cast the expression, as suggested, using

cur.execute("insert into testtable values(%(id)s, %(data)s::json[])", i…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by raw1248
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants