4

I want to have a CHECK constraint on a JSONB column that only permits non-empty JSON objects (only {} with attributes, no other values like [] or JSON primitives).

I only want to check the "root" value, it doesn't matter what is stored in these objects.

How can I do that?

2 Answers 2

3
CHECK(jsonb_typeof(foo)='object' AND foo <> '{}'::JSONB)
Sign up to request clarification or add additional context in comments.

Comments

1

Just like any check constraint and use the <> operators. From the manual:

The standard comparison operators shown in Table 9-1 are available for jsonb, but not for json.

And table 9.1 shows you the not equal operator <>:

create table foo(
    bar jsonb,
    constraint baz check(bar <> '{}'::jsonb)
);

insert into foo(bar) values('{"foo": 1}'::jsonb);
insert into foo(bar) values('{}'::jsonb); -- fails

5 Comments

That's not what I asked. It only prohibits '{}'. I'd still be able to insert '[]' or 'true' for example.
Then put these conditions also in the check constraint using an OR
Well it was basically the question how to do that exactly. But I realised I just overlooked the json_typeof() function - that's why I couldn't just OR it because I had no idea with what. Working now, thanks!
@snøreven what was your solution in the end?
@ian-storm-taylor I just wrote an answer.

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.