JSONB modification functions let you change parts of JSON data stored in a database easily.
JSONB modification functions in PostgreSQL
jsonb_set(target jsonb, path text[], new_value jsonb, create_missing boolean DEFAULT true) RETURNS jsonb jsonb_insert(target jsonb, path text[], new_value jsonb, insert_after boolean DEFAULT false) RETURNS jsonb jsonb_strip_nulls(jsonb) RETURNS jsonb jsonb_delete_path(target jsonb, path text[]) RETURNS jsonb
jsonb_set updates or adds a value at the specified path.
path is an array of keys or indexes to locate where to change inside the JSON.
age to 31.SELECT jsonb_set('{"name": "John", "age": 30}'::jsonb, '{age}', '31'::jsonb);
city with value New York.SELECT jsonb_set('{"name": "John"}'::jsonb, '{city}', '"New York"'::jsonb, true);
green before index 1 in the colors array.SELECT jsonb_insert('{"colors": ["red", "blue"]}'::jsonb, '{colors,1}', '"green"'::jsonb, false);
SELECT jsonb_strip_nulls('{"a":1, "b":null}'::jsonb);
This query shows three JSONB modifications: updating age, adding a new key country, and removing null values.
WITH data AS ( SELECT '{"user": {"name": "Alice", "age": 25, "city": "Boston"}}'::jsonb AS info ) SELECT jsonb_set(info, '{user,age}', '26'::jsonb) AS updated_age, jsonb_set(info, '{user,country}', '"USA"'::jsonb, true) AS added_country, jsonb_strip_nulls('{"a":1, "b":null}'::jsonb) AS no_nulls FROM data;
Paths in jsonb_set use curly braces and commas, like {user,age}.
Use jsonb_strip_nulls to clean JSON objects by removing keys with null values.
Remember that JSONB functions return new JSONB values; they do not change data in place unless used in an UPDATE statement.
JSONB modification functions help update, add, or remove parts of JSON data inside PostgreSQL.
They use paths to locate where to make changes inside nested JSON objects or arrays.
These functions return new JSONB values, so use them in SELECT or UPDATE queries to see changes.