PostgreSQL嵌套JSON查询

rav*_*shi 43 postgresql json 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.
Run Code Online (Sandbox Code Playgroud)

作品

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

为什么必须进行铸造?是不是效率低下?我做错了什么或者这对于postgres JSON支持是否必要?

max*_*kin 76

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

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

select person->'dogs'->0->'breed' from people where id = 77;
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记查看PG支持的JSON运算符的完整列表https://www.postgresql.org/docs/current/static/functions-json.html (5认同)
  • 如果您需要所有品种的列表怎么办?是否支持“选择人-&gt;'狗'-&gt;*-&gt;'品种'”之类的东西 (2认同)
  • @mga,请参阅 [json_array_elements](https://www.postgresql.org/docs/current/functions-json.html#FUNCTIONS-JSON-PROCESSING-TABLE) 函数。`从人 p 中选择狗-&gt;'品种',json_array_elements(p-&gt;'狗') 狗` (2认同)