Issue
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()];
Solution
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 using json_object_agg.
update my_table
set data = (select json_object_agg(key, value) from json_each_text(data));
This approach can be used for other transformations too.
Answered By - Stefanov.sm Answer Checked By - Marilyn (sql.easybugfix Volunteer)
Post a Comment
Post a Comment