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
  • 34,719
  • 24
  • 185
  • 251
Thellimist
  • 3,199
  • 4
  • 29
  • 47

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
  • 22,943
  • 2
  • 61
  • 70