PostgreSQL 输出 JSON 结果
PostGreSQL 从 9.2 开始增加对 JSON 的支持。9.5 已经支持多个 JSON 函数,见 http://www.postgres.cn/docs/9.5/functions-json.html
关于如何查询返回 JSON,这里 有例子,翻译如下:
一个简单的用法就是使用 row_to_json() 函数,它接受 “行值”并返回 JSON 对象:
1 | select row_to_json(tableName) from tableName; |
上面查询语句返回结果类似如下:
1 | { "id" :6013, "text" : "advancement" , "pronunciation" : "advancement" ,...} |
但是有时候我们只需要查询指定的列,那么我们可以使用 row() 结构函数:
select row_to_json(row(id, text)) from
tableName;
上面查询语句返回了我们想要的结果,可惜丢失了列名:
1 | { "f1" :6013, "f2" : "advancement" } |
为了完善这个需求,我们必须创建一个行类型且将结果转换(cast)到这个行类型,或者使用子查询。子查询会更容易一些:
1 2 3 4 | select row_to_json(t) from ( select id, text from tableName ) AS t |
上面查询语句返回了我们希望的样子:
1 | { "id" :6013, "text" : "advancement" } |
另一种常用的技术是 array_agg 和 array_to_json。array_agg 是一个聚合函数 sum 或 count。它聚集成一个 PostgreSQL 数组参数。array_to_json 以 PostgreSQL数组 拼合成一个单一的JSON值。
我们来看看 array_to_json 的用法:
1 2 3 4 | select array_to_json(array_agg(row_to_json(t))) from ( select id, text from tableName ) AS t |
上面查询语句返回了一个由 JSON 对象组成的数组:
1 | [{ "id" :6001, "text" : "abaissed" },{ "id" :6002, "text" : "abbatial" },{ "id" :6003, "text" : "abelia" },...] |
我们来一个复杂的例子(注:这个例子可能有问题):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | select row_to_json(t) from ( select text, pronunciation, ( select array_to_json(array_agg(row_to_json(d))) from ( select part_of_speech, body from definitions where word_id=words.id order by position asc ) d ) as definitions from words where text = 'autumn' |
上面查询语句返回结果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | { "text" : "autumn" , "pronunciation" : "autumn" , "definitions" : [ { "part_of_speech" : "noun" , "body" : "skilder wearifully uninfolded..." }, { "part_of_speech" : "verb" , "body" : "intrafissural fernbird kittly..." }, { "part_of_speech" : "adverb" , "body" : "infrugal lansquenet impolarizable..." } ] } |
Obviously, the SQL to generate this JSON response is far more verbose than generating it in Ruby. Let's see what we get in exchange.(怎么突然蹦出个 Ruby ?)
性能测试
posted on 2016-07-10 18:07 my4piano 阅读(14077) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律