如何将to_jsonb用作row_to_jsonb?关于“多少”的详细信息?

问题描述 投票:7回答:3

我在pg9.4中以“JSON模式”测试了一些查询,现在我正在检查pg9.5是否会带来所有相同的JSONB功能......但是没有row_to_jsonb()函数(!)。 (为什么在基本参数中不是orthogonal instruction set?)

The guide只说“to_jsonb功能提供了相同的功能”。我们在哪里可以检查“多少”?关于这个细节还有其他特定的JSONB指南吗?

json postgresql jsonb postgresql-9.5
3个回答
12
投票

您可以使用to_jsonb()而不是row_to_json(),例如:

with the_table(a, b, c) as (
    select 1, 'alfa', '2016-01-01'::date
)
select to_jsonb(t), row_to_json(t)
from the_table t;

                 to_jsonb                 |             row_to_json             
------------------------------------------+-------------------------------------
 {"a": 1, "b": "alfa", "c": "2016-01-01"} | {"a":1,"b":"alfa","c":"2016-01-01"}
(1 row) 

由于参数的类型(anyelementrecord),第一个应用程序比另一个应用程序更广泛。例如,您可以使用to_jsonb()将Postgres数组转换为json数组,这不能用row_to_json()完成:

select to_jsonb(array['a', 'b', 'c']);

    to_jsonb     
-----------------
 ["a", "b", "c"]
(1 row)

如果在row_to_json()中使用两个参数,您还应该使用jsonb_pretty()

with the_table(a, b, c) as (
    select 1, 'alfa', '2016-01-01'::date
)
select jsonb_pretty(to_jsonb(t)), row_to_json(t, true)
from the_table t;

     jsonb_pretty      |    row_to_json     
-----------------------+--------------------
 {                    +| {"a":1,           +
     "a": 1,          +|  "b":"alfa",      +
     "b": "alfa",     +|  "c":"2016-01-01"}
     "c": "2016-01-01"+| 
 }                     | 
(1 row) 

1
投票

你可以把json转换成jsonb row_to_json(...):: jsonb,不理想,但经常做的伎俩


1
投票

您可以使用to_jsonb作为row_to_json的替代品。

SELECT to_jsonb(rows) FROM (SELECT * FROM table) rows;
© www.soinside.com 2019 - 2024. All rights reserved.