0

I have a table with a json field (NOT json-b) and need to remove a key that exists with some records (or set the value to '').

How can I update this table to do so using SQL?

I've seen this question, but it feels like there should be an easier way for this simple thing.

Neil Middleton
  • 22,105
  • 18
  • 80
  • 134

1 Answers1

2

First: if you are updating values a lot, json may be a bad choice in your database design:

Pure SQL:

UPDATE tbl
SET    json_col = (
   SELECT concat('{', string_agg(to_json(j.key) || ':' || j.value, ','), '}')::json
   FROM   json_each(json_col) j
   WHERE  j.key <> 'delete_this_key'
   )
WHERE  json_col->>'delete_this_key' <> ''; -- only applicable rows!

Related:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228