Simplified syntax for jsonb in PostgreSQL 14

According to the telegram-channel Cross the Join , the repository Postgres fell Komichi , easier to work with jsonb. You can now access parts of jsonb using square brackets, and this works for both reading and writing.







Goodbye jsonb_set and other crutches like data = data - 'a' || '{"a":5}'









A few examples:



We update the value of the object by key. 25 is a number here, but enclosed in quotes because the assigned value must be jsonb







-- (person_data   jsonb)
UPDATE users 
SET person_data['age'] = '25'; 
      
      





The update works with empty (null) jsonb too.







We filter the table by the name = Pasha field. Pasha is a string, but it is also written in the form jsonb: '"Pasha"', so extra double quotes







SELECT * 
FROM users 
WHERE person_data['name'] = '"Pasha"';
      
      





Get the value of the object by the key "age"







SELECT ('{"age": 25}'::jsonb)['age'];
      
      





Or you can specify a long path







SELECT ('{"a": {"b": {"c": 1}}}'::jsonb)['a']['b']['c'];
      
      





Array element by index







SELECT ('[1, "2", null]'::jsonb)[1];
      
      





Most importantly, the changes will be included in postgreSQL 14!







The original idea of ​​the syntax belongs to Oleg Bartunov, implementation - Dmitry Dolgov








All Articles