简体   繁体   中英

How to access Json/Hstore elements in postgresql

I have below data in my table

STUDENT_INFO TABLE

Column Data type
------------------
ID number
STUDENT_DATA hstore

Below is data

ID STUDENT_DATA
1        "config"=>"{"env": "TEST", "student": "10508"}", "payload"=>"{"Score_id": "201814", "Course": ["40359", "40360"]}"

From the above data I want to select Course

My Query is:

select ID,(hstore_to_json(STUDENT_DATA))->'payload'->>'course' 
from STUDENT_INFO 
limit 1

I am getting below error: -

ERROR: cannot extract element from a scalar

Can someone please help me write the query?

You can try this

select ID,((hstore_to_json(STUDENT_DATA ))-> 'payload')::json#>'{Course}' from STUDENT_INFO LIMIT 1

I have tested below query and it does work

SELECT (select '{"Score_id" : 201814, "Course" : [40359, 40360]}'::json)::json#>'{Course}'

And you can also take ref from

https://www.postgresql.org/docs/current/static/functions-json.html

you can consider below kind of example for that

SELECT '{"a":[1,2,3],"b":[4,5,6]}'::json#>'{b,2}'

SELECT '{"a":[1,2,3],"b":[4,5,6]}'::json#>>'{a,2}'

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