arrays - 在 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.
有什么线索吗?
解决方案
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;
推荐阅读
- javascript - 为什么这个递归函数会覆盖第二次调用的值?
- flutter - 将 ListView 的子项对齐到顶部和底部
- javascript - 当他/她单击按钮时,将用户的电子邮件存储在不同的页面上
- python - 改变 xytext 以防止重叠注释
- cucumber - 通过 -Dcucumber.options 传递多个标签(或/和)不会触发我的测试
- excel - 三角形的 VBA 面积
- python - ValueError:无法将字符串转换为浮点数:'thal'
- windows - 创建新文件后资源管理器中的 IShellView::SelectItem
- python - 如何从 Python 中的多个串行输入中读取?
- python - 'ImportError: DLL load failed': import seaborn failed / 仅适用于 conda root 作为 jupyter notebook 中的内核