I have two arrays as shown below, as i concat both the arrays – the ST key value in Array1
is replaced by values in ST
key values in Array2
,
Array 1:
{"ST": ["Bin", "No", "Comp"], "OSS": ["Class"]}
Array 2:
{"ST": ["Pro", "SU"]}"
Expected output:
{"ST": ["Bin", "No", "Comp","Pro", "SU"], "OSS": ["Class"]}
How do I achieve this?
2
Answers
This uses
jsonb_path_query_array
to pull the existing array value from the"ST"
then concatenates it to the array being merged(jsonb_path_query_array
). Thenjsonb_set
replaces the current array associated with the"ST"
key with the new merged array created injsonb_path_query_array
. The CTE(WITH
) is used to not have to repeat the entirejsonb
object.The following will perform the requested operation:
The
||
operator isn’t valid forJSON
, so it will be necessary to castJSON
elements toJSONB
.