简体   繁体   中英

Unnest json string array

I'm using psql and I have a table that looks like this:

id | dashboard_settings
-----------------------
 1 | {"query": {"year_end": 2018, "year_start": 2015, "category": ["123"]}}

There are numerous rows, but for every row the "category" value is an array with one integer (in string format).

Is there a way I can 'unpackage' the category object? So that it just has 123 as an integer?

I've tried this but had no success:

SELECT jsonb_extract_path_text(dashboard_settings->'query', 'category') from table

This returns:

jsonb_extract_path_text | ["123"]

when I want:

jsonb_extract_path_text | 123

Consider:

select dashboard_settings->'query'->'category'->>0 c from mytable

Demo on DB Fiddle :

| c   |
| :-- |
| 123 |

You need to use the array access operator for which is simply ->> followed by the array index:

select jsonb_extract_path(dashboard_settings->'query', 'category') ->> 0
from the_table

alternatively:

select dashboard_settings -> 'query' -> 'category' ->> 0
from the_table

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