你可以使用row_to_json
功能:
select x.id, row_to_json(r.*)::jsonb
from generate_series(1,100) AS x(id)
cross join (select uuid_in(md5(now()::text)::cstring) as lookup_id) as r;
更新
首先,您可以使用uuid
这样您就可以创建唯一的 uid:
CREATE EXTENSION "uuid-ossp";
with cte as (
select
*, uuid_generate_v4() as uuid
from generate_series(1,5) AS x(id)
)
select distinct uuid from cte
------------------------------------------------
"e980c784-8aae-493f-90fb-1091280fe4f7"
"45a80660-3be8-4538-a039-13d97d6306af"
"5380f285-5d6b-467a-a83a-7fdc5c0ebc4c"
"7a435b36-95d3-49fc-808f-359838a866ed"
"3164a544-a2c9-4cd0-b0c4-199a99986cea"
接下来,将其合并到您现有的json
. 目前最愚蠢和最简单的方法可能是这样的:
with cte as (
select
'{"a":1}'::json as j, uuid_generate_v4() as uuid
from generate_series(1,5) AS x(id)
)
select
left(j::text, length(j::text) - 1) || ', "uuid":' || to_json(uuid) || '}'
from cte
但是你也可以写一些函数来合并jsons,或者你可以使用hstore
扩展来合并jsons:
with cte as (
select
id, '{"a":1, "b":2}'::json as data, uuid_generate_v4() as uuid
from generate_series(1,5) AS x(id)
), cte2 as (
select
id,
(
select hstore(array_agg(r.key), array_agg(r.value))
from (
select *
from json_each_text(c.data) as j
union all
select 'uuid', c.uuid::text
) as r
) as data
from cte as c
)
select
id, hstore_to_json(data)
from cte2
而且我确信 PostgreSQL 方面的大专家可以建议更优雅的方式将 json 合并在一起