[GENERAL] JSON objects merge using || operator - Mailing list pgsql-general

From Mickaël Le Baillif
Subject [GENERAL] JSON objects merge using || operator
Date
Msg-id CALtLrz+sQJEOdx4z62UfrkHsK+WsRkpHPiY7JRruQih+YYnEJA@mail.gmail.com
Whole thread Raw
Responses Re: [GENERAL] JSON objects merge using || operator
List pgsql-general
Hello,

I've encountered a disturbing behaviour using the || operator on two jsonb objects extracted from subfields of a common jsonb object.

Let's take a look at this example :

with data as (
    select '{
             "nested1": {"lvl1_k1": "v1"},
             "nested2": {"lvl2_k1":234, "lvl2_k2": "test"}
            }'::jsonb as extra_values,
    
    '{"aaa": 12}'::jsonb as j1,
    '{"bbb": "azerty", "ccc": "qwerty"}'::jsonb as j2
)
select    COALESCE(extra_values->'nested1', '{}')
       || COALESCE(extra_values->'nested2', '{}') as correct,
       
       extra_values->'nested1' || extra_values->'nested2' as bad,
       
       j1 || j2 as correct2
from data
;


I'm expecting to get the same result in columns 'correct' and 'bad', which is :
{"lvl1_k1": "v1", "lvl2_k1": 234, "lvl2_k2": "test"}

But what I'm getting in column 'bad' is only the right operand :
{"lvl2_k1": 234, "lvl2_k2": "test"}

I can recover to my expected behaviour by forcing a cast to jsonb on the second operand :

SELECT extra_values->'nested1' || (extra_values->'nested2')::jsonb

What's your opinion about this ? Is it a bug or an expected behaviour, and if so, how do you explain it ?

Thanks for sharing your knowledge !

pgsql-general by date:

Previous
From: Paolo Saudin
Date:
Subject: [GENERAL] pgAdmin 4 - auto disconnect
Next
From: Melvin Davidson
Date:
Subject: Re: [GENERAL] pgAdmin 4 - auto disconnect