2

我正在最新(9.4)PostgreSQL 中试验新的 JSON/JSONB 对象。首先,我将向您展示我的测试表:

CREATE TABLE "JSONtest" (
    data jsonb
);
COPY "JSONtest" (data) FROM stdin;
{"id": 1, "age": 24, "male": false, "name": "Martha"}
{"id": 2, "age": 49, "male": true, "name": "Jim"}
\.
ALTER TABLE ONLY "JSONtest"
    ADD CONSTRAINT "JSONtest_data_key" UNIQUE (data);

由此,我尝试获取某些列的数据和类型:

SELECT "data"#>'{"male"}' FROM "JSONtest"; -- this returns true|false
SELECT jsonb_typeof("data"#>'{"male"}') FROM "JSONtest"; -- this returns 'boolean'

如文档中所述,如果您在查询中使用单个尖括号,则当前 PostgreSQL 可以将数据作为 json/jsonb 类型返回,或者如果您使用双尖括号,则作为文本返回:

SELECT '{"a":1}'::jsonb->'a' -- this will be of type jsonb
SELECT '{"a":1}'::jsonb->>'a' -- this will be of type string

但我需要 JSON 中数据的实际类型。我尝试的是使用 CAST 函数:

SELECT CAST('{"id":19}'::jsonb->>'a' AS integer) -- this will give back an int type
SELECT CAST('{"id":19}'::jsonb->>'a' AS json_typeof('{"id":19}'::jsonb->>'a')) -- this will obviously give an ERROR, because the type is given as a string

所以我的问题是:

您可以使用指定为字符串的目标类型进行转换吗?

我可以使用存储函数绕过它,因为只有 6 个选项,json_typeof 可以返回什么(对象、数组、布尔值、字符串、数字和 null),但如果有更好的方法,那么我很乐意去.

提前谢谢大家的回答!

--- 编辑 #1 ---

这是我今天想出的一个实验,但它导致了以下文本的错误:CASE types integer and text cannot be match

SELECT
    CASE jsonb_typeof("data"#>"query")
        WHEN 'number' THEN ("data"#>>"query")::int
        WHEN 'string' THEN "data"#>>"query"
        WHEN 'boolean' THEN ("data"#>>"query")::boolean
    END
FROM (
    SELECT
        '{"name" : "Jim", "dogs" : ["Barks", "Fluffy", "Spocky"], "id" : 4}'::jsonb AS "data",
        '{"id"}'::text[] AS "query"
) AS "input"

函数会引起同样的麻烦,因为我需要指定它的返回类型,在这种情况下无法确定。

json_populate_record()json_to_record()也需要指定类型。

4

0 回答 0