0

In PostgreSQL 9.5 to_jsonb function will be added. In 9.4 there is only to_json function.

I'm trying to convert this answer for jsonb but couldn't find an alternative for to_json function. How can I achieve this.

1 Answer 1

4

You can use to_json and then cast it to jsonb :

CREATE OR REPLACE FUNCTION to_jsonb(e anyelement)
RETURNS jsonb 
AS $$
    SELECT to_json(e)::jsonb
$$ LANGUAGE sql;

SELECT to_jsonb('Fred said "Hi."'::text),
       pg_typeof(to_jsonb('Fred said "Hi."'::text));
┌─────────────────────┬───────────┐
│      to_jsonb       │ pg_typeof │
├─────────────────────┼───────────┤
│ "Fred said \"Hi.\"" │ jsonb     │
└─────────────────────┴───────────┘
(1 row)

Naming this function to_jsonb is probably a bad idea though (since there will be a built-in to_jsonb in 9.5, and since it really easy to think this one is a built-in too).

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

Comments

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.