首页 > 解决方案 > 如何以 JSON 形式选择表的列名?

问题描述

我正在尝试以 JSON 格式返回表的列名,其中每个列名是键,数据类型是值。

我有以下代码:

SELECT jsonb_agg(json_build_object(column_name, udt_name::regtype)) AS list 
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'layer_1001'

这会产生以下结果:

[{"id": "integer"}, {"geom": "geometry"}, {"address": "text"}, {"start_date": "timestamp without time zone"}]

但我需要代码产生以下结果:

{"id": "integer", "geom": "geometry", "address": "text", "start_date": "timestamp without time zone"}

有人知道该怎么做吗?

标签: sqljsonpostgresql

解决方案


使用该功能json_objectjsonb_object

它们接受两个参数,键和值的数组,并且都必须可序列化为文本

SELECT 
  JSON_OBJECT(ARRAY_AGG(column_name::TEXT), ARRAY_AGG(udt_name::text)) 
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'mytable'

推荐阅读