2

Is there a way to construct a jsonb with only a numeric value in it?

For example,

SELECT pg_typeof(('{"a":1}'::jsonb) -> 'a');

indicates that ('{"a":1}'::jsonb) -> 'a' has the jsonb type and it only contains a numeric value 1.

But how do I create a jsonb with 1 in it directly without constructing and destructing an object?

Direct type casting does not seem to work:

# SELECT 1::jsonb;
ERROR: cannot cast type integer to jsonb
LINE 1: SELECT 1::jsonb;
asked May 14, 2022 at 21:40
0

1 Answer 1

3

You need to cast from a string, not from a number: '1'::jsonb. This is because using '1' means that the result is actually a constant, whereas 1 is a runtime conversion.

to_jsonb(1) also works, but I think this uses a runtime conversion.

SELECT pg_typeof('1'::jsonb), jsonb_typeof('1'::jsonb);
pg_typeof jsonb_typeof
jsonb number

db<>fiddle

Paul White
95.3k30 gold badges439 silver badges689 bronze badges
answered May 15, 2022 at 14:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.