1

We have grids that we have custom filters for and you can save the filters as a JSON object to a particular table, tblUserPersistedValue (along with a user field). So we are updating the page and the filters are going from single-select IDs to multi-select IDs on four different filters.

Curent JSON:

'{
"ProductGroupID":1,
"TerminalID":1,
"CarrierID":1221,
"RegionID":21,
"DriverDateFilter":0,
"DriverStartDate":"0001-01-01T00:00:00",
"DriverEndDate":"0001-01-01T00:00:00"
}';

Where You see "TerminalID":1, I would like to change it to "TerminalID":[1] so we don't break any user's settings when we make the update. Unfortunately i am unable to figure out how to create an int array with JSON_MODIFY. I am almost there, but it's wrapping the value i'm saving in quotes, and that won't parse into an int array during deserialization.

I have never worked with json directly in sql before and I must be missing something simple. How do i fix it? If it's impossible to overwrite the existing entry, I could also make a new TerminalIDs entry to parse into and remove the old one.

The ultimate goal is to do this for every record in the table, once for each of four fields.

2
  • Using only JSON functions and without string manipulations - SELECT @json = JSON_MODIFY(@json, '$.TerminalID', JSON_MODIFY(N'[]', 'append $', CONVERT(int, JSON_VALUE(@json, '$.TerminalID')))). Commented Apr 28, 2020 at 7:58
  • doesn't append count as as a string manipulation? Commented Apr 29, 2020 at 19:33

1 Answer 1

2
declare @j nvarchar(max) = N'{"ProductGroupID":1,"TerminalID":1,"CarrierID":1221,"RegionID":21,"DriverDateFilter":0,"DriverStartDate":"0001-01-01T00:00:00","DriverEndDate":"0001-01-01T00:00:00"}';
select @j = json_modify(@j, '$.TerminalID', json_query(concat('[', json_value(@j, '$.TerminalID') ,']')));
select @j;
Sign up to request clarification or add additional context in comments.

1 Comment

I just managed to get this to work using json_modify just as you answered this. You get the rep.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.