0

I'm on PostgreSQL 13.2. I have a table with a JSONB column, and it stores JSONs that are a list of objects:

"[{\"MyKey\":\"ValueXYZ\",\"Counter\":0}, {\"MyKey\":\"ValueABC\",\"Counter\":3}]"

When I test this column for a type with jsonb_typeof() like so:

select jsonb_typeof(i.my_column) as col_type
from items i 
where i.id = 342

I get string. Which tells me this value is a scalar, and I'm wondering if maybe it wasn't inserted properly.

The error that is bothering me is I am trying to parse the column with something like this:

select jsonb_array_elements(i.my_column)
from items i 

and I see the error:

SQL Error [22023]: ERROR: cannot extract elements from a scalar

What is going on? Is there a way to fix this?

2 Answers 2

1

Yes, it got inserted wrong. It contains a scalar, which happens to be holding the string representation of a JSON array. The string representation of a JSON array is a different thing than an actual JSON array.

You can extract the string value from the scalar, then cast that string into a jsonb. #>>'{}' will extract the string out of a scalar.

select jsonb_array_elements((i.my_column#>>'{}')::jsonb)
from items i ;

Although you should fundamentally fix the problem, by re-storing the values correctly.

update items set my_column = (my_column#>>'{}')::jsonb where jsonb_typeof(my_column)='string';

But of course you should fix whatever is doing the incorrect insertions first.

Sign up to request clarification or add additional context in comments.

Comments

0

Looks like a quoting issue. Consider:

test=> SELECT jsonb_typeof(jsonb '[{"MyKey":"ValueXYZ","Counter":0}, {"MyKey":"ValueABC","Counter":3}]') AS col_type;
 col_type 
----------
 array
(1 row)

Comments

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.