【问题标题】:SQL Error while trying to extract nested json data尝试提取嵌套的 json 数据时出现 SQL 错误
【发布时间】:2021-02-08 23:41:45
【问题描述】:

我正在运行 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"
  }
]

【问题讨论】:

  • 请向我们展示您想要的样本数据结果。
  • 我想知道为什么我的 SQL 查询失败了。 sql 查询应该成功返回我的 SQL 编辑器中的数据。它将有五列(responseId、chatId、data、text、uiActionCode)。具体来说,数据列应该包含数据中的所有内容:{}; text 应该有“testQuestion2”作为其列中的值,而 uiActionCode 将有 TextWithButton。

标签: sql arrays json postgresql unnest


【解决方案1】:

如果我正确地遵循了这一点,那么一层解除嵌套就足够了。然后,您可以使用 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'

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-24
    • 2012-05-02
    • 2021-09-18
    • 2020-05-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    相关资源
    最近更新 更多