简体   繁体   English

获取 Postgres 表数据为 Json 不带字段名称

[英]Get Postgres Table Data as Json Without Field Names

I want to convert Postgres table data to JSON without repeated field names at JSON result.我想将 Postgres 表数据转换为 JSON 结果中没有重复的字段名称 JSON 结果。 When I use current PostgreSQL json functions, JSON results look likes similar to this: [{"id":"1234","name":"XYZ"},....] .当我使用当前的 PostgreSQL json 函数时,JSON 结果看起来类似于: [{"id":"1234","name":"XYZ"},....] But by this way, all field names unnecessarily exists on every row.但是通过这种方式,所有字段名称都不必要地存在于每一行上。 So we does not prefer this way for the network bandwith.所以对于网络带宽我们不喜欢这种方式。

We want to get JSON result such as [["1234","XYZ"],....] .我们想要得到 JSON 结果,例如[["1234","XYZ"],....] So total length of result json string will be much smaller.所以结果 json 字符串的总长度会小得多。

Well, you could use json(b)_build_array() to turn each record to an array - this requires you to enumerate the column names:好吧,您可以使用json(b)_build_array()将每条记录转换为数组 - 这需要您枚举列名:

select jsonb_build_array(id, name) js from mytable

If you want all rows in a single array of arrays, then you can use aggregation on top of this:如果您想要 arrays 的单个数组中的所有行,那么您可以在此之上使用聚合:

select jsonb_agg(jsonb_build_array(id, name)) res from mytable

Demo on DB Fiddle : DB Fiddle 上的演示

select jsonb_agg(jsonb_build_array(id, name)) res 
from (values(1, 'foo'), (2, 'bar')) as t(id, name)
| res                      |
| :----------------------- |
| [[1, "foo"], [2, "bar"]] |

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

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