to_json() 是一个系统函数,用于将SQL值转换为 json。
to_json() 在 PostgreSQL 9.3 中被添加。
用法
to_json ( anyelement ) → json
请注意,row_to_json() 提供了处理SQL复合值的函数,但可选地可以添加换行符。
变更历史
- PostgreSQL 9.3
- 添加(提交 38fb4d97)
示例
to_json() 的基本用法示例
postgres=# SELECT to_json('hello, world'::text);
to_json
----------------
"hello, world"
(1 row)
postgres=# SELECT to_json(row(97, 'foo', ARRAY[1,2,3]));
to_json
-----------------------------------
{"f1":97,"f2":"foo","f3":[1,2,3]}
(1 row)
由于 to_json() 接受 anyelement 作为其参数,因此模棱两可的数据类型需要提供显式转换。
postgres=# SELECT to_json('hello, world');
ERROR: could not determine polymorphic type because input has type unknown
参考资料
- PostgreSQL文档: JSON创建函数
