【问题标题】:PostgreSQL: parse multiple values to each rowPostgreSQL:为每一行解析多个值
【发布时间】:2021-10-25 12:31:13
【问题描述】:

我在 PostgreSQL 表中有这个 JSON:

[{"desc": "Select the setting that you will do the recordings under.", "name": "ambient", "type": "dropdown", "values": ["", "Indoors + High + Loud", "Indoors + High + Normal", "Indoors + Low + Normal", "Indoors + Low + LowVolume", "Outdoors + High + Normal", "Outdoors + Low + Loud", "Outdoors + Low + Normal", "Outdoors + Low + LowVolume"]}, {"desc": "Select the noise type that you will do the recordings under.", "name": "Noise type", "type": "dropdown", "values": ["", "Human Speech", "Ambient Speech", "Non-Speech"]}, {"desc": "What is the most accurate description of where you are recording? (O: for Outdoors, I: for Indoors)", "name": "surroundings", "type": "dropdown", "values": ["", "O: Backyards/Park with people talking/music", "O: Busy intersection/Transportation station/Construction", "O: Walking/Cycling in noisy streets", "O: Windy outside (Beach, Deck etc.)", "O: Car with Engine on (Window open in streets)", "O: In backyard/a park/streets alone/with not much noise", "O: Other", "I: Home with TV/noisy appliance on", "I: Home with people talking/kids", "I: Inside noisy public buildings/places", "I: Home with not much noise", "I: Other"]}, {"desc": "If you selected Other, please describe your surroundings below. (Skip if not)", "name": "other_surroundings", "type": "string"}]

值“名称”包含来自列表,例如 [""、“室内 + 高 + 响”、“室内 + 高 + 正常”、“室内 + 低 + 正常”、“室内 + 低 + 低音量”、“室外+ 高 + 普通”、“户外 + 低 + 响”、“户外 + 低 + 普通”、“户外 + 低 + 低音量”]

我需要在另一个表中为此列表中的每个项目创建行

["", "Indoors + High + Loud", "Indoors + High + Normal", "Indoors + Low + Normal", "Indoors + Low + LowVolume", "Outdoors + High + Normal", "Outdoors + Low + Loud", "Outdoors + Low + Normal", "Outdoors + Low + LowVolume"]

例子,

""
"Indoors + High + Loud" etc.

我尝试使用这个查询:

-- For multiple choice from JSON
SELECT
  s.projectid,
  s.prompttype,
  el.inputs->>'name' AS name,
  el.inputs->>'desc' AS desc,
  el.inputs->>'values' AS values,
  s.created,
  s.modified
FROM source_redshift.staticprompts AS s,
     jsonb_array_elements(s.inputs::jsonb) el(inputs);

但它仅从 JSON 解析列表。并非键“值”中的每个项目。

【问题讨论】:

  • 你想解析“values”属性中的字符串吗?

标签: sql json postgresql


【解决方案1】:

使用嵌套的jsonb_array_elements,例如:

SELECT 
  jsonb_array_elements(
    jsonb_array_elements(s.inputs->'inputs')->'values')
FROM staticprompts AS s

您的查询应如下所示:

SELECT
  s.projectid,
  s.prompttype,
  el.inputs->>'name' AS name,
  el.inputs->>'desc' AS desc,
  el.inputs->>'values' AS values,
  jsonb_array_elements(el.inputs->'values'),
  s.created,
  s.modified
FROM staticprompts AS s,
     jsonb_array_elements(s.inputs::jsonb->'inputs') el(inputs);

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2015-03-21
    相关资源
    最近更新 更多