尝试提取嵌套的json数据时出现SQL错误

问题描述

我正在运行SQL查询提取嵌套的JSON数据。

SELECT watsonResponse.responseId,watsonResponse.chatId,d.*
FROM watson_response_table watsonResponse
         CROSS JOIN LAteraL (
    SELECT d2.*
    FROM jsonb_array_elements(watsonResponse.watsonresponse_output) AS d(events)
             CROSS JOIN LAteraL (
        SELECT d2.events ->> 'data'         AS watsonResponse_ouput_data,d2.events ->> 'text'         AS watsonResponse_output_text,d2.events ->> 'uiActionCode' AS watsonResponse_output_uiActionCode
        FROM jsonb_array_elements(d.events) AS d2(events)
        ) d2
    WHERE d.events ->> 'uiActionCode' = 'TextWithButton'
    ) d;

它失败并显示消息 sql错误[22023]:错误:无法从对象中提取元素

我正在使用Postgressql 11+。这是JSON的样子,

[
  {
    "text": [
      "Some text!"
    ],"uiActionCode": "textOnly"
  },{
    "data": {
      "type": "options","options": [
        { "label": "test","value": "testvalue" },{ "label": "test2","value": "testvalue2" },{
          "label": "test3","value": "testQuestion?"
        }
      ]
    },"text": ["testQuestion2?"],"uiActionCode": "TextWithButton"
  }
]

解决方法

如果我正确地遵循了此步骤,则只需进行一次嵌套即可。然后,您可以使用JSON访问器来获取所需的结果:

SELECT 
    r.responseId,r.chatId,d.events ->> 'uiActionCode' AS output_uiActionCode,d.events -> 'text' ->> 0    AS output_text,d.events -> 'data'          AS output_data,FROM watson_response_table watsonResponse r
CROSS JOIN LATERAL jsonb_array_elements(r.watsonresponse_output) AS d(events)
WHERE d.events ->> 'uiActionCode' = 'TextWithButton'

请注意,访问器->->>之间存在重要区别。前者返回一个对象,而后者返回一个文本值。您需要根据每个字段需要执行的操作仔细选择正确的运算符。