简体   繁体   English

从JSON PostgreSQL提取

[英]Extract from JSON PostgreSQL

I have three columns: 我有三列:

  • id, ID,
  • state, 州,
  • curr_status curr_status

The curr_status column has data that's formatted like this: curr_status列的数据格式如下:

[{"id": 123, "created_at": "2017-07-17T19:49:19.125865", "status": "student"}]

I want to SELECT id, state, and extract the status for each row into a new column so it says student. 我想选择id,状态,并将每行的状态提取到新列中,这样它说出了Student。 New to working with JSON, how would I write the code to do that? JSON的新手,我该如何编写代码来做到这一点?

You didn't specify what should happen if the array contains more than one element. 您没有指定如果数组包含多个元素会发生什么情况。

But to get the value for the first array element, you can use the -> operator to get the first array element, then use the ->> operator to get 但是要获取第一个数组元素的值,可以使用->运算符获取第一个数组元素,然后使用->>运算符获取

select id, state, 
       curr_status -> 0 ->> 'status' as status
from the_table;

One option would be using json_array_elements function which firstly will split the elements of the array and then filter : 一种选择是使用json_array_elements函数,该函数首先将拆分数组的元素,然后进行过滤:

select id , state, js ->> 'status' as st_special
  from tab, --> your table with columns id, state, curr_status(of type json)
       jsonb_array_elements(curr_status) as js
 where js ->> 'status' = 'student';

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM