J. Finn
J. Finn

Reputation: 159

How do I check the type of a field contained in a JSONB?

I'm hoping this is a fairly simple question with a simple answer.

In PostgreSQL I have a table with a Answer column that is a jsonb. As of right now, the data that can be stored in the column can be empty or quite varied. Some examples include:

Yes, we store a field called Answer in our column called Answer. Not sure why, but that is how it is.

I want to be able to test if the JSON attribute Answer contains a string or an array. But I don't know how, and I must be wording my searches incorrectly. I'm not finding anything concrete. I already know how to check if Answer exists. Just can't tell what it contains.

Does anyone know how I would do this? Or if there isn't a way, what I need to do instead to query this data?

Upvotes: 1

Views: 165

Answers (2)

J. Finn
J. Finn

Reputation: 159

func.jsonb_typeof(<TableNameHere>.answer.op('->')('Answer')) == "string" seems to do the job.

Upvotes: 1

Laurenz Albe
Laurenz Albe

Reputation: 247063

The condition would be:

WHERE jsonb_typeof(answer->'Answer') = 'string'

Upvotes: 2

Related Questions