Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

postgresql - Extract multiple values from JSONB in Postgres

I have a table that looks like this:

id attrs
1 {"a":{"kind":"kind_1", "value":"val_1"}, "b":{"kind":"kind_2", "value":"val_2"}
2 {"c":{"kind":"kind_3", "value":"val_1"}}
3 {"a":{"kind":"kind_1", "value":"val_1"}, "d":{"kind":"kind_4", "value":"val_4"}, .....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a JSON Path query:

select distinct v.item #>> '{}'
from the_table t
  cross join jsonb_array_elements(jsonb_path_query_array(t.attrs, '$.**.value')) as v(item);

The v.item #>> '{}' is a trick to convert a scalar JSON value to text (because casting it wouldn't work)

Alternatively you can use jsonb_each() twice:

select distinct v.value
from the_table t
  cross join jsonb_each(t.attrs) as i(key, item)
  cross join jsonb_each_text(i.item) as v(key, value)
where v.key = 'value'  


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...