如何在postgresql中解析JSON

时间:2015-09-17 08:54:42

标签: json postgresql

我的数据库中有一个表,其中包含字符变化列,此列包含json。我需要编写一个查询,它将以某种方式将这个json解析为单独的列。

我找到 json_each 函数here,但我无法理解如何使用它。

2 个答案:

答案 0 :(得分:20)

我想通了,伙计们

如果我有桌子 enter image description here

我可以轻松编写查询

SELECT 
   id, 
   data::json->'name' as name
FROM books;

它将导致

enter image description here

我也可以尝试获取不存在的列

SELECT 
   id, 
   data::json->'non_existant' as non_existant
FROM books;

在这种情况下,我会得到空的结果

enter image description here

答案 1 :(得分:3)

太棒了,谢谢分享。我发现您可以更深入地了解:

SELECT 
   id, 
   data::json->'name' as name,
   data::json->'author' ->> 'last_name' as author
FROM books;