14

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

该指南 只说“to_jsonb 函数提供了几乎相同的功能”我们在哪里可以检查“多少”? 还有其他关于此详细信息的特定 JSONB 指南吗?

4

3 回答 3

24

您可以只使用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) 

由于参数的类型(anyelementvs record),第一个比另一个具有更广泛的应用。例如,您可以使用 将 Postgres 数组转换为 json 数组to_jsonb(),但不能使用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) 
于 2017-01-16T22:41:24.740 回答
4

您可以to_jsonb用作row_to_json.

SELECT to_jsonb(rows) FROM (SELECT * FROM table) rows;
于 2017-01-16T21:29:44.590 回答
1

您可以将 json 转换为 jsonb row_to_json(...)::jsonb,虽然不理想但通常可以解决问题

于 2016-05-18T09:06:09.843 回答