【问题标题】:How parse multiple parameters in JSON?如何解析 JSON 中的多个参数?
【发布时间】:2021-10-25 08:58:38
【问题描述】:

我在 PostgreSQL 表中有 JSON:

{"inputs": [{"desc": "How many people does the video contain?", "name": "Number of People", "type": "dropdown", "values": ["", "Only 1", "2-3", "3+"]}, {"desc": "What is the camera position?", "name": "Movement", "type": "dropdown", "values": ["", "Fixed position", "Moving"]}, {"desc": "From which angle did you shoot the video?", "name": "Shoot Angle", "type": "dropdown", "values": ["", "Frontal recording", "Tight angle: 10-40 degree", "Wide angle: 40-70 degree"]}, {"desc": "From which distance did you shoot the video?", "name": "Distance", "type": "dropdown", "values": ["", "Near/Selfie", "Mid (3-6 ft)", "Far (>6 ft)"]}, {"desc": "What is the video lighting direction?", "name": "Lighting Direction", "type": "dropdown", "values": ["", "Front lit", "Side lit", "Back lit"]}, {"desc": "What is the video background?", "name": "Background", "type": "dropdown", "values": ["", "Outdoors", "In office", "At home", "Plain background"]}, {"desc": "What is the topic in your speech?", "name": "Topic", "type": "dropdown", "values": ["", "Arts and Media", "Business", "Education", "Entertainment", "Food/Eating", "Nutrition", "Healthcare ", "High School Life", "Mental Health", "News", "Technology", "Morals and Ethics", "Phones and Apps", "Sports", "Science"]}]}

此 JSON 包含多个“名称”键(和其他键)。

如何解析每个“名称”键的值?

我试试:

SELECT
        s.projectid,
        s.prompttype,
        s.inputs::jsonb#>>'{inputs,0,desc}' AS desc,
        s.inputs::jsonb#>>'{inputs,0,name}' AS name,
        s.inputs::jsonb#>>'{inputs,0,values}' AS values,
        s.created,
        s.modified
FROM source_redshift.staticprompts AS s;

但我只得到一个 JSON 值。

【问题讨论】:

    标签: sql json postgresql


    【解决方案1】:

    你必须像这样解析 jsonb 数组。使用{inputs,0,...},您只检索 jsonb 数组的第一个元素。请改用jsonb_array_elements

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

    演示:db<>fiddle

    【讨论】:

    • 不需要使用 LATERAL,没有它查询也能正常工作。
    • @FrankHeikens 这是真的!这就是您重用代码时发生的情况:-D 感谢您指出
    • 伙计们,我收到一个错误:[42883] 错误:函数 jsonb_array_elements(字符变化)不存在提示:没有函数与给定的名称和参数类型匹配。您可能需要添加显式类型转换。
    • @ViktorAndriichuk 这意味着s.inputs 不是jsonb 类型。您需要将其投射:jsonb_array_elements(s.inputs::jsonb->'inputs')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-23
    • 2012-02-07
    • 1970-01-01
    • 2016-07-29
    • 1970-01-01
    相关资源
    最近更新 更多