【问题标题】:How to get to objects nested in a jsonb array?如何获取嵌套在 jsonb 数组中的对象?
【发布时间】:2021-11-29 15:37:11
【问题描述】:

我一直在尝试引用函数jsonb_to_recordset() 中的列,而不是以原始形式输入它。我们说的表结构是这样的:

CREATE TABLE clusters (
cluster_id bigserial PRIMARY KEY,
cluster_name text,
cluster_restrictors jsonb);

单个cluster_restrictor 如下所示:

{
  "min_av_grade": null, 
  "min_tot_grade": null, 
  "restrictor_reqs": [{"grade": "2:1","restriction": ["Physics"]}],
  "restrictor_type": "BSc"
}

我最近一次尝试检索类似表格的结果是:

WITH arrb AS (
  SELECT jsonb_agg(cluster_restrictors) 
from clusters
) 
SELECT jsonb_to_recordset(jsonb_agg) AS (restrictor_type text) 
FROM arrb;

以语法错误结尾。

这么快,如何从中得到?

 cluster_id | cluster_name |                                                                          cluster_restrictors
------------+--------------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------
          3 |              | [{"min_av_grade": null, "min_tot_grade": null, "restrictor_reqs": [{"grade": "2:1", "restriction": ["Physics"]}], "restrictor_type": "BSc"}]
          4 |              | [{"min_av_grade": null, "min_tot_grade": null, "restrictor_reqs": [{"grade": "2:1", "restriction": 7}, {"grade": "2:2", "restriction": 8}], "restrictor_type": "BSc"}]

到这里:

 restrictor_type |                             restrictor_reqs
-----------------+--------------------------------------------------------------------------
 BSc             | [{"grade": "2:1", "restriction": 7}, {"grade": "2:2", "restriction": 8}]
 BSc             | [{"grade": "2:1", "restriction": ["Physics"]}]

可以做什么?

【问题讨论】:

  • 你能举例说明一下输出应该是什么样子吗
  • 我多次阅读您的问题,但仍然不知道您到底在问什么。请澄清。
  • 什么是restrictor_type?你想选择什么?为什么在实际查询中使用jsonb_agg(cluster_restrictors) 而不是引用clusters.cluster_restrictors
  • 已作出澄清。感谢您的参与
  • 我建议新标题与旧标题一样编辑,似乎专注于错误的工具。

标签: sql json postgresql jsonb


【解决方案1】:

似乎您可以只使用(更简单的)jsonb_array_elements() 而不是 jsonb_to_recordset(),然后使用普通字段提取运算符:

SELECT cr.value ->> 'restrictor_type' AS restrictor_type
     , cr.value ->  'restrictor_reqs' AS restrictor_reqs
FROM   clusters c, jsonb_array_elements(c.cluster_restrictors) cr;

见:

【讨论】:

    猜你喜欢
    • 2019-09-26
    • 1970-01-01
    • 2015-05-20
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2016-12-20
    • 2019-02-17
    • 1970-01-01
    相关资源
    最近更新 更多