如何在 postgresql 中解析 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32626261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:03:10  来源:igfitidea点击:

How to parse JSON in postgresql

jsonpostgresql

提问by Ivan Ursul

I have a table in my database, which contains character varying column and this column has json. I need to write a query, which will somehow parse this json into separate columns.

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

I found json_eachfunction herebut I can't understand how to work with it.

我在这里找到了json_each函数但我不明白如何使用它。

回答by Ivan Ursul

I figured it out, guys

我想通了,伙计们

if I have a table books enter image description here

如果我有桌书 在此处输入图片说明

I can easily write a query

我可以轻松编写查询

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

And it will result in

它会导致

enter image description here

在此处输入图片说明

I can also try to get non-existent column

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

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

And it this case I will get empty result

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

enter image description here

在此处输入图片说明

回答by hit3k

Awesome, thanks for sharing. I found that you can go deeper like:

厉害了,谢谢分享。我发现你可以更深入:

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