简体   繁体   中英

Extract from JSON PostgreSQL

I have three columns:

  • id,
  • state,
  • curr_status

The curr_status column has data that's formatted like this:

[{"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. New to working with JSON, how would I write the code to do that?

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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