I have a table with a JSON column that is full of different keys and some of the values in it are numbers but I want all the values to be text. For example, I have {"budget": 500, "budget_id": 100, ...[dozens more keys]}
, but I want it to be {"budget":"500", "budget_id": "100"}
. I am hoping there is a single query that will blindly spit back a JSON object whose values are all text. Something along the lines of:
UPDATE my_table
SET data = data || --python-sql psuedo-code -> [key:quote_literal(value) for key in data.keys()];
2
Answers
i think based off of the helpful earlier answer given in Postgres - Update all values in a JSON object to be text I was able to adjust the query:
Here it is. First flatten the JSON into a set of key-value pairs using
json_each_text
(value as text) and aggregate back into JSON usingjson_object_agg
.This approach can be used for other transformations too.
It might be a better idea to make a view instead of modifying the original data: