使用列值作为对象键创建json [英] Create json with column values as object keys

查看:118
本文介绍了使用列值作为对象键创建json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的表:

I have a table defined like this:

CREATE TABLE data_table AS (
  id bigserial,
  "name" text NOT NULL,
  "value" text NOT NULL,
  CONSTRAINT data_table_pk PRIMARY KEY (id)
);

INSERT INTO data_table ("name", "value") VALUES
('key_1', 'value_1'),
('key_2', 'value_2');

我想从该表内容中获取一个JSON对象,它看起来像这样:

I would like to get a JSON object from this table content, which will look like this:

{
  "key_1":"value_1",
  "key_2":"value_2"
}

现在,我正在使用客户端应用程序将结果集解析为JSON格式.可以通过postgresl查询来完成此操作吗?

Now I'm using the client application to parse the result set into JSON format. Is it possible to accomplish this by a postgresl query?

推荐答案

如果您使用的是9.4,则可以执行以下操作:

If you're on 9.4 you can do the following:

$ select json_object_agg("name", "value") from data_table;
           json_object_agg
----------------------------------------------
{ "key_1" : "value_1", "key_2" : "value_2" }

这篇关于使用列值作为对象键创建json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆