简体   繁体   English

nginx + PostgreSQL:返回JSON对象

[英]nginx + PostgreSQL: return JSON object

I like to run a PostgreSQL 10 server as a backend and nginx with ngx_postgres as a frontend. 我喜欢运行PostgreSQL 10服务器作为后端,使用ngx_postgres作为前端的nginx。 The database stores data in JSONB format: 数据库以JSONB格式存储数据:

=# CREATE TABLE dump (
   id   bigserial primary key,
   data jsonb     not null
);

The data can be queried like: 数据可以像这样查询:

=# SELECT data FROM dump;

Using ngx_postgres, one can access the PostgreSQL database directly from nginx: 使用ngx_postgres,可以直接从nginx访问PostgreSQL数据库:

upstream postgresql {
    postgres_server localhost dbname=default user=user password=secret;
}

server {
    listen 80;

    location /postgresql/ {
        rds_json          on;

        postgres_pass     postgresql;
        postgres_query    HEAD GET "SELECT data FROM dump"
        postgres_rewrite  no_rows 410;
        postgres_output   rds;
    }
}

But the result is returned as text, with escaped double quotes, not JSON as intended: 但是结果以文本形式返回,并带有转义的双引号,而不是预期的JSON:

[{"data":"{\"id\": \"00ce160e5cbb49b9bc2ee6f243f87841\", \"name\": \"foo\"}"}] 

How can I return the result of the query as an JSON object? 如何将查询结果作为JSON对象返回?

You can try the c2h5oh framework. 您可以尝试使用c2h5oh框架。 It is a fast and lightweight framework for building web applications using power of Nginx and PostgresSQL 这是一个快速轻巧的框架,用于使用Nginx和PostgresSQL的功能构建Web应用程序

https://github.com/genosse/c2h5oh/ https://github.com/genosse/c2h5oh/

After several attempts I was able to output JSON by changing the nginx configuration. 经过几次尝试,我能够通过更改nginx配置来输出JSON。 The nginx module headers-more has to be installed and loaded for this to work: 必须安装和加载nginx模块标头 -more,才能正常工作:

server {
    listen 80;

    location /postgresql/ {
        rds_json          off;

        postgres_pass     postgresql;
        postgres_query    HEAD GET "SELECT json_agg(data) FROM dump"
        postgres_rewrite  no_rows 410;
        postgres_output   text;
        more_set_headers  'content-type: application/json';
    }
}

First, the PostgreSQL output format has to be set to text . 首先,必须将PostgreSQL输出格式设置为text Then, the default content type must be overridden with more_set_headers . 然后,必须使用more_set_headers覆盖默认的内容类型。 The result served by nginx is valid JSON. nginx提供的结果是有效的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM