PostgreSQL嵌套JSON查询

时间:2014-07-24 21:31:47

标签: json postgresql psql postgresql-9.3

在PostgreSQL 9.3.4上,我有一个名为“person”的JSON类型列,其中存储的数据格式为{dogs: [{breed: <>, name: <>}, {breed: <>, name: <>}]}。我想在索引0处检索狗的品种。以下是我运行的两个查询:

不起作用

db=> select person->'dogs'->>0->'breed' from people where id = 77;
ERROR:  operator does not exist: text -> unknown
LINE 1: select person->'dogs'->>0->'bree...
                                 ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

作品

select (person->'dogs'->>0)::json->'breed' from es_config_app_solutiondraft where id = 77;
 ?column?
-----------
 "westie"
(1 row)

为什么需要进行类型转换?是不是效率低下?我做错了什么或者这对于postgres JSON支持是否必要?

1 个答案:

答案 0 :(得分:58)

这是因为运算符->>将JSON数组元素作为文本。您需要使用强制转换将其结果转换回JSON。

您可以使用运算符->消除此冗余强制转换:

select person->'dogs'->0->'breed' from people where id = 77;
相关问题