openresty上游postgres调用一个函数,它自己返回一个json

时间:2016-12-02 14:07:06

标签: json postgresql nginx openresty

假设您有一个函数返回postgresQL数据库中定义的json。

CREATE OR REPLACE FUNCTION test() RETURNS JSON AS $$
  SELECT
  '[
    {"fName":"John","lName":"Doe"},
    {"fName":"Jane","lName":"Doe"}
  ]'::JSON;
$$ 
LANGUAGE SQL STRICT IMMUTABLE;


SELECT test();
-------------------------------------
 [                                  
     {"fName":"John","lName":"Doe"},
     {"fName":"Jane","lName":"Doe"} 
 ]

此外你有一个包含Postgres Nginx模块的Nginx(openresty) 使用以下配置文件:

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {

    upstream database {
        postgres_server localhost dbname=example user=postgres;
        postgres_keepalive max=200 overflow=reject;
    }

    server {
        listen 8080;
        location /test/ {
                postgres_pass database;
                rds_json  on;
                postgres_query    HEAD GET  "SELECT test()";
                postgres_rewrite  HEAD GET  no_rows 410;
        }
    }
}

rds_json on; 所有引号都在输出中转义,如下所示:

curl http://localhost:8080/test/
[{"test":"[\n    {\"fName\":\"John\",\"lName\":\"Doe\"},\n    {\"fName\":\"Jane\",\"lName\":\"Doe\"}\n  ]"}]

如果我将 rds_json设置为关闭; 我收到格式正确的json,但返回字符串以一些尴尬的标志开始和结束:

@^C^@^@^@^@^@^@^B^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^A^@^@<80>r^@^D^@test^AL^@^@^@[
    {"fName":"John","lName":"Doe"},
    {"fName":"Jane","lName":"Doe"}
  ]^@

有没有办法在结果对象中删除其他符号,或者在第一种情况下没有转义所有双引号?

由于

1 个答案:

答案 0 :(得分:0)

我找到了一个理由。实际上它是微不足道的。而不是将openresty格式化输出到json。对不起,我的问题打扰了社区。 我必须正确设置标题:

worker_processes  1;
error_log logs/error.log;
events {
    worker_connections 1024;
}
http {

    upstream database {
        postgres_server localhost dbname=example user=postgres;
        postgres_keepalive max=200 overflow=reject;
    }

    server {
        listen 8080;
        location /test/ {
                postgres_pass database;
                postgres_query    HEAD GET  "SELECT test()";
                more_set_headers  'Content-Type: application/json';
                postgres_rewrite  HEAD GET  no_rows 410;
        }
    }
}