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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Thellimist
  • 3,757
  • 5
  • 31
  • 49

1 Answers1

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).

Marth
  • 23,920
  • 3
  • 60
  • 72