Postgres - how select jsonb key value pairs as colums?

313 Views Asked by At

having records in test table like so (metrics column is jsonb type):

id     name      metrics
1      machine1  {"metric1": 50, "metric2": 100}
2      machine2  {"metric1": 31, "metric2": 46}

I would like to select the metrics as additional columns, e.g. (pseudo-code):

Select *, json_each(test.metrics) from test;

to get the result like:

id  name       metric1   metric2 
1   machine1   50        100
2   machine2   31        46

Is this even possible?

2

There are 2 best solutions below

3
On BEST ANSWER

Use the ->> operator:

select id, name, 
       metrics ->> 'metric1' as metric1,
       metrics ->> 'metric2' as metric2
from test;
2
On

You can simply use ->>

demo:db<>fiddle

SELECT
    id,
    name,
    metrics ->> 'metric1' as metric1,
    metrics ->> 'metric2' as metric2
FROM t

Note, that now the metric columns are of type text. If you want to them to be of type integer, you need to cast them additionally:

(metrics ->> 'metric1')::int