Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove double quotes from the return of a function in PostgreSQL

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?

like image 780
Leo Avatar asked Dec 02 '16 09:12

Leo


People also ask

How do you escape double quotes in Postgres?

Quotes and double quotes should be escaped using \.

How do I remove a character from a string in postgresql?

The LTRIM() function removes all characters, spaces by default, from the beginning of a string. The RTRIM() function removes all characters, spaces by default, from the end of a string. The BTRIM function is the combination of the LTRIM() and RTRIM() functions.

How do you remove quotes from a string?

To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.

How do I remove double quotes from a string in SSIS?

Ensure your Text qualifier is set to " – this will remove the quotes around your fields. As we have no headers in the file, untick the “Column names in the first data row” checkbox. Preview the file to ensure it looks OK.


1 Answers

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)
like image 174
Craig Ringer Avatar answered Oct 14 '22 02:10

Craig Ringer