首页 > 解决方案 > 在 Postgresql 中提取 jsonb - 同一 jsonb 字段中的字典和数组结构

问题描述

我正在使用 postgresql,我在数据集上有这个表,有些列是 jsonb。

SELECT 
external_id as cod,
title as name,
objectives
FROM table

因此,“目标”列的结果是这样的:

{"blocks":
    [
        {"key":"dek2k",
        "text":"Objetivo Geral",
        "type":"unstyled",
        "depth":0,
        "inlineStyleRanges":
            [
            {"offset":0,"length":14,"style":"fontsize-12pt"},
            {"offset":0,"length":14,"style":"fontfamily-Arial"},
            {"offset":0,"length":14,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{"text-align":"start"}},
        {"key":"ct1vn",
        "text":"Conhecer e aplicar ferramentas para análise da mídias em sua respectiva relação com a cognição e o design,",
        "type":"unstyled","depth":0,"inlineStyleRanges":
            [
            {"offset":0,"length":216,"style":"color-rgb(0,0,0)"},
            {"offset":0,"length":216,"style":"fontsize-12pt"},
            {"offset":0,"length":216,"style":"fontfamily-Arial"},
            {"offset":0,"length":216,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{}},
        {"key":"8jshq",
        "text":"","type":"unstyled","depth":0,
        "inlineStyleRanges":[],
        "entityRanges":[],"data":{}},
        {"key":"avq4h",
        "text":"tendo como ênfase os estudos das materialidades dos meios de comunicaçõe e seus aspectos sensoriais.",
        "type":"unstyled",
        "depth":0,
        "inlineStyleRanges":
            [
            {"offset":0,"length":23,"style":"color-rgb(0,0,0)"},
            {"offset":0,"length":23,"style":"fontsize-12pt"},
            {"offset":0,"length":23,"style":"fontfamily-Arial"},
            {"offset":0,"length":23,"style":"fontsize-14"}
            ],
        "entityRanges":[],
        "data":{}}
    ],
"entityMap":{}
}

我只想得到“文本”中的结果。有时它只有一个“文本”值,有时它有多达 15 个或更多。

我需要的是表中所有行的这样的结果:

 cod      |      name      | objectives
----------+-----------------+----------
 1        | A              | Objetivo Geral Conhecer e aplicar ferramentas para análise da mídias em sua respectiva relação com a cognição e o design, tendo como ênfase os estudos das materialidades dos meios de comunicaçõe e seus aspectos sensoriais.

有什么线索吗?

标签: arrayspostgresqldictionaryjsonb

解决方案


json 函数可以string_agg()实现您想要的。

使用WITH ORDINALITY保证text元素的正确排序。

SELECT t.external_id as cod,
       t.title as name,
       string_agg(a.block->>'text', ' ' ORDER BY rn) as objectives
  FROM "table" t
       CROSS JOIN LATERAL jsonb_array_elements(t.objectives->'blocks')
                           WITH ORDINALITY as a(block, rn)
 GROUP BY t.external_id, t.title;

推荐阅读