Home > Mobile >  how to split a JSON column into multiple as I showed here in Postgres
how to split a JSON column into multiple as I showed here in Postgres

Time:02-10

One of the column of my table is JSON like this:

timestamp values
xxxx [{"d_st":1601,"d_val":2.731},{"d_st":1602,"d_val":0.465},{"d_st":1603,"d_val":0.422},{"d_st":1604,"d_val":2.803},{"d_st":1605,"d_val":2.771},{"d_st":1606,"d_val":260.352}]

How could I split it into d_st and d_val like this:

timestamp dst dval
xxxx 1601 2.731
xxxx 1602 0.465
and so on

I used this:

SELECT values ->> "d_st" AS dst, values ->> 'd_val' AS val 
FROM ss;

but can't get any value, just two empty column, why is that?

CodePudding user response:

for this purpose, you can use json_to_recordset or jsonb_to_recordset function depending on the data type of values column as follows:

Select ss.timestamp, x.d_st, x.d_val
From ss Cross Join Lateral json_to_recordset(ss.values) As x(d_st int, d_val numeric)

Result:

timestamp d_st d_val
xxxx 1601 2.731
xxxx 1602 0.465
xxxx 1603 0.422
xxxx 1604 2.803
xxxx 1605 2.771
xxxx 1606 260.352

db<>fiddle

  • Related