Skip to content

Instantly share code, notes, and snippets.

@skaag
Created December 15, 2014 22:07
Show Gist options
  • Select an option

  • Save skaag/9a0d95878bf117c5b765 to your computer and use it in GitHub Desktop.

Select an option

Save skaag/9a0d95878bf117c5b765 to your computer and use it in GitHub Desktop.
SELECT CASE
WHEN ("json" -> "key_to_set") IS NULL THEN "json"
ELSE COALESCE(
(SELECT ('{' || string_agg(to_json("key") || ':' || "value", ',') || '}')
FROM (SELECT *
FROM json_each("json")
WHERE "key" <> "key_to_set"
UNION ALL
SELECT "key_to_set", to_json("value_to_set")) AS "fields"),
'{}'
)::json
END
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment