How to convert literal \\u sequences into UTF-8? [

2019-01-29 00:59发布

问题:

This question already has an answer here:

  • Convert escaped Unicode character back to actual character in PostgreSQL 1 answer

I am loading data dump from external source and some strings contain \uXXXX sequences for the UTF8 chars, like this one:

\u017D\u010F\u00E1r nad S\u00E1zavou

I can check the contents by using E'' constant in psql, but cannot find any function/operator to return me proper value.

I'd like to ask, if it's possible to convert this string with unicode escapes into normal UTF8 without using PL/pgSQL functions?

回答1:

I don't think there is a built in method for that. Easiest way I can think of is the plpgsql function you wanted to avoid:

CREATE OR REPLACE FUNCTION str_eval(text, OUT t text) AS
$func$
BEGIN
EXECUTE 'SELECT E''' || replace($1, '''', '''''') || ''''
USING $1
INTO t;
END
$func$ LANGUAGE plpgsql IMMUTABLE STRICT;

The updated version safeguards against SQLi and is faster, too.