我无法从PostgreSQL中的JSON类型列中提取数据

时间:2019-02-28 16:00:59

标签: sql json postgresql

我想从json类型列中提取数据以将它们插入表中以便规范化数据库。

JSON类型列称为“信息”,下面是一个记录示例:

[ { "major" : "International business", 
    "end" : "2007", 
    "name" : "Annamalai University",
    "degree" : "Master Degree", 
    "start" : "2005", "desc" : "" 
  }, 
  { "major" : "Mechanical Engineering", 
    "end" : "1990", 
    "name" : "Bharathidasan University", 
    "degree" : "Bachelor Degree", 
    "start" : "1990", "desc" : "" 
  }
]

这是我的代码:

SELECT id,
       (json_array_elements(info)->>'education')::json ->> 'key' AS key1 
FROM perfiles
WHERE id = 1252710;

这是我想要获得的结果: table result example

我应该如何查询?

预先感谢

3 个答案:

答案 0 :(得分:0)

尝试这样的事情

select *
from (
  select
  json_to_recordset(info) as ed(major text, end int, name text, degree text, start int, desc text)
  from perfiles 
  where id = 1252710
)

参考:https://www.postgresql.org/docs/9.5/functions-json.html

答案 1 :(得分:0)

使用json_to_recordset

    SELECT  x.*
FROM pjson_table
   , json_to_recordset(myjson::json) x 
        (  major text
         , "end" text
         , name text
         , degree text
         , start text
         ,"desc" text
        )

demo link

 major                  end      name                   degree         start
International business  2007    Annamalai University    Master Degree   2005
Mechanical Engineering  1990    Bharathidasan University    Bachelor Degree 1990

答案 2 :(得分:0)

您可以将cross join lateraljson_array_elements一起使用,并在选择中列出元素

SELECT  p.id, 
           j->>'major'::text AS major, 
           (j->>'end')::int  AS "end", 
           j->>'name'        AS NAME, 
           j->>'degree'      AS degree, 
           j->>'start'       AS start, 
           j->>'desc'        AS "desc" 
FROM  perfiles p 
CROSS JOIN LATERAL json_array_elements(info) AS j

或通过在json_to_recordset子句中指定列列表来使用FROM

select p.id,
j.* FROM   perfiles p
  cross join lateral json_to_recordset(info) 
as j(major text, "end" int, name text, degree text, start int, "desc" text);

Demo