I’m using ::text[] to convert an array inside a JSON column, like in the example below:
Imagine sometable to have a JSON column called ‘object’ with a structure like the following:
{ "properties": ["string", "someotherstring"] }
I am querying the db like this:
SELECT * FROM db.sometable
WHERE 'string' = ANY (ARRAY[object -> 'properties']::text[]);
I am expecting ARRAY[object -> 'properties']::text[]
to return some kind of list of strings, like the following:
{"string", "someotherstring"}
…but, after some debugging, I realized it’s returning some wierd s*** like the following:
{"["string", "someotherstring"]"}
Basically, it is treating the whole array as a string! What could be the cause?
PS: I understand that I should use other functions or filters, but the real query I’m working on is highly dynamic and way more complicated than the example I provided. ::text[] seems to be the only option I have
Thank you in advance for your help!
I am expecting ::text[] to convert a JSON array into a list of strings, but it is actually considering the whole array as a string.
3
Answers
Use
json_array_elements_text
combined withARRAY
to convert a json array into list of text valuesTEXT[]
:This is another method for looking for an element within a json array :
Demo here
Hope this solves your problem
The table content: a screenshot of the table content
it gives the following output:
a screenshot of the solution output
As you can see the records contain "{" and "}"; I simply removed them using
regexp_replace
function.The SQL now being like this:
The results: a screenshot of the final results
There is no reason to convert the json to a Postgres array. You need a proper operator.
Test it in db<>fiddle.
Read about json functions and operators in the documentation.