![](/img/trans.png)
[英]postgreSQL how to convert multiple rows from a table to an array of JSON
[英]How to convert a JSON to table in PostgreSQL
我有一個表格,其中的一列中有一些具有這種形式的 JSON:
{
"header": {
"hardwareId": 0,
"Id": "xxx",
"manufacturerId": "",
"timestampMsg": "xxx"
},
"Info": [{
"timestampPos": "xxx",
"coordinate": {
"latitude": xxx,
"longitude": xxxx
},
{
"timestampPos": "xxx",
"coordinate": {
"latitude": xxx,
"longitude": xxxx
},
{
"timestampPos": "xxx",
"coordinate": {
"latitude": xxx,
"longitude": xxxx
},
{
"timestampPos": "xxx",
"coordinate": {
"latitude": xxx,
"longitude": xxxx
}
}]
}
我需要為任何 JSON 提取一個包含三列的表:Timestamp、Lat 和 Lon。 我該怎么做?
謝謝。
您可以將cross join
與jsonb_array_elements
一起使用:
select t.js -> 'header' -> 'Id' id,
v.value -> 'timestampPos' tStamp,
v.value -> 'coordinate' -> 'latitude' lat,
v.value -> 'coordinate' -> 'longitude' long
from tbl t cross join jsonb_array_elements(t.js -> 'Info') v
只要您的 json 有效(不像您問題中的示例),您就可以在jsonb_array_elements()
cross join lateral
,然后取消引用並轉換值:
select t.id,
(e.el->>'timestampPos')::timestamp as timestamppos,
(e.el->'coordinate'->>'latitude')::float8 as latitude,
(e.el->'coordinate'->>'longitude')::float8 as longitude
from a_table t
cross join lateral jsonb_array_elements(t.jdata->'Info') e(el);
db<> 在這里擺弄
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.