有什么方法可以从 PostgreSQL table 中获取 json 格式的数据,它具有不同的字段而不是 json 数据类型字段?
Is there any way to fetch data in json format from PostgreSQL table which has different field not the json data type field?
我在 PostgreSQL 中有一个 table,它有像 id,name,city,mob 这样的字段
等等。我在 PostgreSQL 中得到了 json 数据类型,我们可以在其中
以 json 格式存储数据,但我不想使用 json 数据类型。
我想获取这些 table 字段 (id,name,city,mob),它们是普通字段,而不是我想要的 json 格式的 json 数据类型字段
我想要假设我的table是一个table,它有id、name、city、mob、dob作为字段和
现在我想执行如下查询:
select name,city from mytable where id=5;
这个查询应该 return 输出像 {"name":"xyz","city":"abc"}
那么我该怎么做,应该查询什么?
使用row_to_json()
:
select row_to_json(t)
from (
select name,city from mytable
where id=5
) t
派生的 table 是创建具有专有列名的记录类型所必需的。 row_to_json((name,city))
不会实现这一点。
编辑:
如果您想要 table 中的 all 列(不仅仅是问题中显示的两个列),那么您不需要派生的 table :
select row_to_json(mytable)
from mytable
where id = 5;
我在 PostgreSQL 中有一个 table,它有像 id,name,city,mob 这样的字段 等等。我在 PostgreSQL 中得到了 json 数据类型,我们可以在其中 以 json 格式存储数据,但我不想使用 json 数据类型。
我想获取这些 table 字段 (id,name,city,mob),它们是普通字段,而不是我想要的 json 格式的 json 数据类型字段
我想要假设我的table是一个table,它有id、name、city、mob、dob作为字段和
现在我想执行如下查询:
select name,city from mytable where id=5;
这个查询应该 return 输出像 {"name":"xyz","city":"abc"}
那么我该怎么做,应该查询什么?
使用row_to_json()
:
select row_to_json(t)
from (
select name,city from mytable
where id=5
) t
派生的 table 是创建具有专有列名的记录类型所必需的。 row_to_json((name,city))
不会实现这一点。
编辑:
如果您想要 table 中的 all 列(不仅仅是问题中显示的两个列),那么您不需要派生的 table :
select row_to_json(mytable)
from mytable
where id = 5;