PostgreSQL 9.5:将json数据显示到表中

时间:2016-11-01 04:57:00

标签: json postgresql

我在表table_json中有以下记录:

表格

  id        doc
  ---------------------------------------
  1 
            {"name":"Shaw",
                 "address":{"line1":"L1",
                            "line2":"L2",
                            "zipcode":"12345"
                           }
            }

注意:列doc的类型为json。现在我想将json数据打印成形式 以下一个。

预期输出

  id    name    address
  --------------------------
   1    Shaw    L1,L2,12345

1 个答案:

答案 0 :(得分:3)

在横向联接中使用json_each_text()

with a_table (id, doc) as (
values
(1, '{
    "name": "Shaw", 
    "address":{
        "line1":"L1",
        "line2":"L2",
        "zipcode":"12345"
        }
    }'::json)
)
select 
    id, 
    doc->>'name' as name, 
    string_agg(value, ',') as address
from a_table, 
lateral json_each_text(doc->'address')
group by 1, 2;

 id | name |   address   
----+------+-------------
  1 | Shaw | L1,L2,12345
(1 row)