4

I have a column called metadata which has format TEXT but contains stuff that's usually a JSON. I want to select a certain value in it (metadata :: JSON -> 'register' ->> 'date' for instance) but if the JSON is badly formatted or if the field doesn't exist I get an error. Can I make that column just return a NULL value when it would get an error instead?

1 Answer 1

7

You can write a stored procedure that tries to cast to json and returns null of failure. Something like this:

create function to_json(t text) returns json as $$
begin
  return t::json;
exception when invalid_text_representation then
  return null;
end;
$$ language plpgsql;

and then use to_json(metadata) -> 'register' ->> 'date'.

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

2 Comments

Works fine but I would avoid creating a function named as existing built in PostgreSQL functions postgresql.org/docs/current/…
is such a to_json function that returns NULL on error instead of throwing still not built into psql as of 2024?

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.