How to convert postgresql 9.4 jsonb to object without function/server side language

China☆狼群 提交于 2019-11-30 19:05:33
Erwin Brandstetter

Use jsonb_populate_record() (or json_populate_record() for json) with a well known row type as target. You can use a temp table to register a type for ad-hoc use (if you can't use an existing table or custom composite type):

CREATE TEMP TABLE obj(a int, b int, c int, d int);

Then:

SELECT t.id, d.*
FROM   test t
     , jsonb_populate_record(null::obj, t.data) d;

Or use jsonb_to_record() (or json_to_record() for json) and provide a column definition list with the call:

SELECT t.id, d.*
FROM   test t
     , jsonb_to_record(t.data) d(a int, b int, c int, d int);

Or extract and cast each field individually:

SELECT id, (data->>'a')::int AS a, (data->>'b')::int AS b
         , (data->>'c')::int AS c, (data->>'d')::int AS d
FROM   test;

All three work for json and jsonb alike. Just use the respective function variant.

Related:

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!