Neil Middleton
Neil Middleton

Reputation: 22238

Updating JSON in postgres

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.

Upvotes: 0

Views: 98

Answers (1)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 657002

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:

Upvotes: 2

Related Questions