Remove double quotes from the return of a function in PostgreSQL

JsonDatabasePostgresqlFunction

Json Problem Overview


I have the following function in PostgreSQL

CREATE OR REPLACE FUNCTION public.translatejson(JSONB, TEXT)
RETURNS TEXT
AS
$BODY$
   SELECT ($1->$2)::TEXT
$BODY$
LANGUAGE sql STABLE;

When I execute it I receive the values surrounded by double quotes. For example:

SELECT id, translatejson("title", 'en-US') AS "tname" FROM types."FuelTypes";

in return I get a table like this

-------------------
| id | tname      |
-------------------
| 1  | "gasoline" |
| 2  | "diesel"   |
-------------------

The values in the 'title' column are in JSON format: { "en-US":"gasoline", "fr-FR":"essence" }. How I can omit the double quotes to return just the string of the result?

Json Solutions


Solution 1 - Json

The -> operator returns a json result. Casting it to text leaves it in a json reprsentation.

The ->> operator returns a text result. Use that instead.

test=> SELECT '{"car": "going"}'::jsonb -> 'car';
 ?column? 
----------
 "going"
(1 row)

test=> SELECT '{"car": "going"}'::jsonb ->> 'car';
 ?column? 
----------
 going
(1 row)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeoView Question on Stackoverflow
Solution 1 - JsonCraig RingerView Answer on Stackoverflow