I have a JSON column in a table which looks like this:
{
"Id": 123 "Filters": [{
"FilterType": "Category",
"Values": {
"23098": "Power Tools",
"12345": "Groceries"
}
}, {
"FilterType": "Distributor",
"Values": {
"98731": "Acme Distribution",
"12345": "Happy Star Supplies"
}
}
]
}
Note that the "12345" is in there twice on purpose, because the lookups for distributors might be different than the lookups for Categories, so it's not truly a duplicate, and this is important.
I'm storing this JSON data in a column, and the user has renamed "Groceries" to "Food stuffs". So it's still 12345 but now I want to search and replace Groceries with Foodstuffs in every JSON Field that has a FilterType of Category and ID 12345.
I've figured out how to find the data that has it, but the JSON_MODIFY update statement has me all crossed up because
- I don't know how to reference a particular key/value pair in json path used in JSON_MODIFY
- When I do, I still have to specify that the modification should only happen to the value 12345 in the same block as "Category", NOT Distributor.
Can anyone help me construct the T-SQL Magic that would be smart enough to replace the proper key value pair(s) in this? (there could also be a third filter of type Category which also had 12345: Groceries. I omitted it for brevity's sake, but you must assume there could N different filters each of FilterType "Category" and Key = 12345.
JSON_MODIFYsupports absolute paths, but that's about it. There is nothing that will allow sibling filters like XPath, and nothing that constructs paths. Of course you can write it (T-SQL is Turing complete, if we want to get technical) but that doesn't count as magic. What you can do is laboriously deconstruct the objects (usingOPENJSON), perform the logic with regular relational logic (CASE WHEN ... THEN 'Foodstuffs' ELSE value END) and then reconstruct things withFOR JSON PATH, but that is very painful.