JSON列到SQL中的列

mm5n2pyu  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(75)

我有一个数据集,其中一列是JSON格式的。我想把它转换成SQL中的几个列。我正在DBeaver中使用Postgres
JSON列如下。我想把abcde3中的所有内容放在几列中

{
   "abcde1":"INFO",
   "abcde2":"MOTOR",
   "abcde3":{
      "COLOR":"WHITE",
      "DATE_BIRTH":"05/09/1992",
      "GENDER":"F",
      etc
   },
   "PARTNER_ID":"XYZOEKF",
   "NAME":"ANYTHING",
   "userId":"1204923"
}

我已经在SQL中尝试了下面的代码,但它没有工作

with jsonvalue as (
 select '{json_column_in_dataset}'::jsonb as jsonvalues
 FROM my_table
 WHERE any_condition = true
)

select 
        jsonvalues -> 'COLOR',
        jsonvalues -> 'DATE_BIRTH',
        etc
                    from jsonvalue

如何在SQL中转换它?

nqwrtyyt

nqwrtyyt1#

将'json_column_in_dataset'更改为表中JSON列的名称,将'my_table'更改为表的名称。

WITH 
  abc AS (
    SELECT '{
      "abcde1": "INFO",
      "abcde2": "MOTOR",
      "abcde3": {
        "COLOR": "WHITE",
        "DATE_BIRTH": "05/09/1992",
        "GENDER": "F"
      },
      "PARTNER_ID": "XYZOEKF",
      "NAME": "ANYTHING",
      "userId": "1204923"
    }'::jsonb AS jsonvalues
  ),
  jsonvalue AS (
    SELECT
      jsonvalues::jsonb AS jsonvalues
    FROM
      abc
    -- WHERE
    --    any_condition = true
  )
SELECT
   jsonvalues -> 'abcde3' ->> 'COLOR' AS color,
   jsonvalues -> 'abcde3' ->> 'DATE_BIRTH' AS date_of_birth,
   jsonvalues -> 'abcde3' ->> 'GENDER' AS gender
   -- Add more columns as needed
FROM
   jsonvalue;

相关问题