从JSON中提取int,string,boolean等作为其对应的PostgreSQL类型

jpm*_*c26 6 postgresql json

我觉得我必须在这里错过一些简单的东西,但是我已经查看了PostgreSQL关于JSON和JSON运算符和函数的文档,并没有看到任何解释它的东西.

在PostgreSQL中很容易将事物变成JSON:

SELECT *, pg_typeof(j) FROM (VALUES
(to_json(5)),
(to_json(true)),
(to_json('foo'::TEXT))
) x (j);
Run Code Online (Sandbox Code Playgroud)

会给我一个很好的jsons 结果集:

   j   | pg_typeof
-------+-----------
 5     | json
 true  | json
 "foo" | json
Run Code Online (Sandbox Code Playgroud)

但是,如何将这些json值转换原始类型?当然,我不希望能够在一个结果集中完成所有操作,因为类型不一致.我只是个人意思.

我尝试了很多东西

铸造肯定不起作用:

SELECT to_json(5)::NUMERIC;
Run Code Online (Sandbox Code Playgroud)

ERROR:  cannot cast type json to numeric
Run Code Online (Sandbox Code Playgroud)

如果我试图滥用这样的json_populate_record功能:

SELECT json_populate_record(null::INTEGER, to_json(5));
Run Code Online (Sandbox Code Playgroud)

我明白了

ERROR:  first argument of json_populate_record must be a row type
Run Code Online (Sandbox Code Playgroud)

在PG 9.4中,我可以很容易地告诉类型:SELECT json_typeof(to_json(5));give number,但这并没有帮助我实际提取它.

也不json_to_record(也是9.4):

SELECT * FROM json_to_record(to_json(5)) x (i INT);
Run Code Online (Sandbox Code Playgroud)

让我另一个错误:

ERROR:  cannot call json_to_record on a scalar
Run Code Online (Sandbox Code Playgroud)

那么如何将json"标量"(显然是PG称之为"scalars")转换为相应的PG类型?

我对9.3和9.4感兴趣; 9.2只是奖金.

jpm*_*c26 9

布尔值和数字的最简单方法似乎是首先转换为TEXT然后转换为适当的类型:

SELECT j::TEXT::NUMERIC
FROM (VALUES ('5.4575e6'::json)) x (j)
-- Result is 5457500, with column type NUMERIC
SELECT j::TEXT::BOOLEAN
FROM (VALUES ('true'::json)) x (j)
-- Result is t, with column type BOOLEAN
Run Code Online (Sandbox Code Playgroud)

这会留下字符串,您可以在此处获取引用的值:

SELECT j::TEXT
FROM (VALUES (to_json('foo'::TEXT))) x (j)
-- Result is "foo"
Run Code Online (Sandbox Code Playgroud)

显然,我的问题的特定部分已经得到解决.您可以通过将文本值包装在数组中然后将其解压缩来解决它:

SELECT array_to_json(array[j])->>0
FROM (VALUES (to_json('foo'::TEXT))) x (j)
-- Result is foo, with column type TEXT.
Run Code Online (Sandbox Code Playgroud)