1

Let me explain:

[1] [no error]

SELECT (('{"a": null}'::JSONB)->>'a')::INT;

[2] [error here]

SELECT (t.value::TEXT)::INT FROM jsonb_each(('{"a": null}'::JSONB)) AS t
  • I have to use jsonb_each function.

  • How can i make SQL number 2 return null?

1
  • PostgreSQL version: "PostgreSQL 10.12" Commented Feb 29, 2020 at 12:00

2 Answers 2

1

In your first example you use ->> which returns the value as a text data type. The equivalent "for each" function is jsonb_each_text() which also returns the value as text. jsonb_each returns each value as a JSONB value

SELECT t.value::INT 
FROM jsonb_each_text(('{"a": null}'::JSONB)) AS t
Sign up to request clarification or add additional context in comments.

Comments

1

You can do this for example:

SELECT nullif(t.value::text,'null')::int
FROM jsonb_each(('{"a": null}'::JSONB)) AS t

Best regards,
Bjarni

2 Comments

Both answers are better than mine. I tried to use row_to_json. I will accept the native one. Thank you!
Yes. @a_horse_without_name does this the right way - as usually. I used jsonb_each as you specified you needed to use that function for some reason :-)

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.