Postgresql 中的 JSON 输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11198625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON output in Postgresql
提问by Ali
I hope I am not missing something very obvious here,
I want to get JSON output from a postgres function (I imagine many other had already needed this) and I'd be happy to install an extension of contrib functions on my server,
我希望我没有在这里遗漏一些非常明显的东西,
我想从 postgres 函数中获取 JSON 输出(我想很多其他人已经需要这个了)并且我很乐意在我的服务器上安装 contrib 函数的扩展,
Is there any way to get JSON output from sql or plpgsql functions (or with help of db-server-side python)? Specifically I want to get my record[]
results as JSON.
有没有办法从 sql 或 plpgsql 函数(或在 db-server-side python 的帮助下)获取 JSON 输出?具体来说,我想将record[]
结果作为 JSON。
采纳答案by madth3
There is built-in support for JSON since PostgreSQL 9.2and it has increased with many other features in more recent versions(For example: JSON functions in PostgreSQL 0.4).
自PostgreSQL 9.2起就内置了对 JSON 的支持,并且在最近的版本中增加了许多其他功能(例如:PostgreSQL 0.4 中的 JSON 函数)。
Specially the row_to_json
converts a record into a JSON object and the array_to_json
turns arrays into JSON arrays.
特别是row_to_json
将记录转换为 JSON 对象并将array_to_json
数组转换为 JSON 数组。
For example, both functions can be combined to easily turn the results of a SELECT
query into JSON:
例如,可以将两个函数结合起来,轻松地将SELECT
查询结果转换为 JSON:
SELECT array_to_json(array_agg(row_to_json(t))) FROM
(SELECT col1, col2, col3 FROM example_table) t
回答by Craig Ringer
Use record_to_json(...)from 9.2, now available backported to 9.1.
使用9.2 中的record_to_json(...),现在可以向后移植到 9.1。
回答by Sandeep
On the server install:sudo apt-get install postgresql-plpython-9.4
在服务器上安装:sudo apt-get install postgresql-plpython-9.4
Then on your Postgres server:
然后在您的 Postgres 服务器上:
CREATE EXTENSION IF NOT EXISTS plpythonu;
CREATE LANGUAGE plpythonu;
CREATE OR REPLACE FUNCTION prettyprint_json(data text)
RETURNS json
AS $$
import json
return json.dumps(json.loads(data), indent=4)
$$ LANGUAGE plpythonu;
回答by pd40
The postgresqlplpythonplugin certainly lets you do this using the pythonjsonlibrary.
在PostgreSQL的plpython插件肯定让你做这个使用Python的JSON库。
You can do something like this:
你可以这样做:
CREATE OR REPLACE FUNCTION myschema.tojsonfunc()
AS $$
import json;
jsonStr = json.dumps(myrecord)
$$ LANGUAGE plpythonu;