You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中如何从JSON文本提取哈希数组键值并逗号分隔展示?

Solution to Extract Comma-Separated Genre Texts from JSON Text Field

Got it, let's get that query working exactly how you need it. The issue with your current statement is that you're pulling the entire genres array instead of extracting just the text values and combining them. Here's how to fix it:

Step-by-Step Breakdown

Since your data field is stored as text, we'll first cast it to jsonb (it’s more efficient for array operations than plain json) and then:

  • Use jsonb_array_elements to "unpack" the genres array into individual rows, each holding one genre object
  • Extract the text value from each genre object using ->>'text' (the double arrow returns a plain text string instead of a JSON value)
  • Use string_agg to stitch all the genre texts into a single comma-separated string
  • Group by the book’s id to ensure each book gets one row with its combined genres

Final Working Query

SELECT
  id,
  string_agg(genre->>'text', ',') AS genre_list
FROM
  books,
  jsonb_array_elements((data::jsonb)->'genres') AS genre
WHERE
  (data::jsonb)->'genres' IS NOT NULL
GROUP BY
  id
LIMIT 1;

Handling Edge Cases

If some books might have an empty genres array or the field is null, use COALESCE to return a clean default value (like an empty string) instead of null:

SELECT
  id,
  COALESCE(string_agg(genre->>'text', ','), '') AS genre_list
FROM
  books,
  jsonb_array_elements((data::jsonb)->'genres') AS genre
GROUP BY
  id
LIMIT 1;

Example Output

For your sample data {"genres":[{"text":"Crime","id": "1"},{"text":"Romance","id": "5"}],"name":"Harry Potter"}, this query will return:

idgenre_list
1Crime,Romance

内容的提问来源于stack exchange,提问作者Surya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:31:27