@@ -286,6 +286,7 @@ typedef struct StripnullState
286286 JsonLexContext * lex ;
287287 StringInfo strval ;
288288 bool skip_next_null ;
289+ bool strip_in_arrays ;
289290} StripnullState ;
290291
291292/* structure for generalized json/jsonb value passing */
@@ -4460,8 +4461,19 @@ sn_array_element_start(void *state, bool isnull)
44604461{
44614462 StripnullState * _state = (StripnullState * ) state ;
44624463
4463- if (_state -> strval -> data [_state -> strval -> len - 1 ] != '[' )
4464+ /* If strip_in_arrays is enabled and this is a null, mark it for skipping */
4465+ if (isnull && _state -> strip_in_arrays )
4466+ {
4467+ _state -> skip_next_null = true;
4468+ return JSON_SUCCESS ;
4469+ }
4470+
4471+ /* Only add a comma if this is not the first valid element */
4472+ if (_state -> strval -> len > 0 &&
4473+ _state -> strval -> data [_state -> strval -> len - 1 ] != '[' )
4474+ {
44644475 appendStringInfoCharMacro (_state -> strval , ',' );
4476+ }
44654477
44664478 return JSON_SUCCESS ;
44674479}
@@ -4493,6 +4505,7 @@ Datum
44934505json_strip_nulls (PG_FUNCTION_ARGS )
44944506{
44954507 text * json = PG_GETARG_TEXT_PP (0 );
4508+ bool strip_in_arrays = PG_NARGS () == 2 ? PG_GETARG_BOOL (1 ) : false;
44964509 StripnullState * state ;
44974510 JsonLexContext lex ;
44984511 JsonSemAction * sem ;
@@ -4503,6 +4516,7 @@ json_strip_nulls(PG_FUNCTION_ARGS)
45034516 state -> lex = makeJsonLexContext (& lex , json , true);
45044517 state -> strval = makeStringInfo ();
45054518 state -> skip_next_null = false;
4519+ state -> strip_in_arrays = strip_in_arrays ;
45064520
45074521 sem -> semstate = state ;
45084522 sem -> object_start = sn_object_start ;
@@ -4520,12 +4534,13 @@ json_strip_nulls(PG_FUNCTION_ARGS)
45204534}
45214535
45224536/*
4523- * SQL function jsonb_strip_nulls(jsonb) -> jsonb
4537+ * SQL function jsonb_strip_nulls(jsonb, bool ) -> jsonb
45244538 */
45254539Datum
45264540jsonb_strip_nulls (PG_FUNCTION_ARGS )
45274541{
45284542 Jsonb * jb = PG_GETARG_JSONB_P (0 );
4543+ bool strip_in_arrays = false;
45294544 JsonbIterator * it ;
45304545 JsonbParseState * parseState = NULL ;
45314546 JsonbValue * res = NULL ;
@@ -4534,6 +4549,9 @@ jsonb_strip_nulls(PG_FUNCTION_ARGS)
45344549 JsonbIteratorToken type ;
45354550 bool last_was_key = false;
45364551
4552+ if (PG_NARGS () == 2 )
4553+ strip_in_arrays = PG_GETARG_BOOL (1 );
4554+
45374555 if (JB_ROOT_IS_SCALAR (jb ))
45384556 PG_RETURN_POINTER (jb );
45394557
@@ -4564,6 +4582,11 @@ jsonb_strip_nulls(PG_FUNCTION_ARGS)
45644582 (void ) pushJsonbValue (& parseState , WJB_KEY , & k );
45654583 }
45664584
4585+ /* if strip_in_arrays is set, also skip null array elements */
4586+ if (strip_in_arrays )
4587+ if (type == WJB_ELEM && v .type == jbvNull )
4588+ continue ;
4589+
45674590 if (type == WJB_VALUE || type == WJB_ELEM )
45684591 res = pushJsonbValue (& parseState , type , & v );
45694592 else
0 commit comments