I have a SQL variable which stores the following JSON object:
{"name": "Dan", "country": "Japan", "job": "manager"}
My goal is to sort the object based on the keys alphabetically and return it
{"country": "Japan", "job": "manager", "name": "Dan"}
. The keys will vary for different json objects.
Unfortunately, I am unable to use OpenJson because of compatibility issue and it may stay that way. So I tried using JSON_TABLE command. My overall goal is to:
- Create a table with two columns, keys and values, keys will hold all the keys in the json object, whereas values will hold the corresponding value for the key in that row.
- Use order by key to return the result in sorted way
- Return the result in a json object format
However, I am getting stuck at the first step. I created two variables to store the json arrays for the keys and values separately using JSON_KEYS
and JSON_EXTRACT
. Then, I combined them into another variable, which has the following structure:
{key: ['name', 'country', 'job'], value:['Dan', 'Japan', 'manager']}
. Finally, I used JSON_Table
on it with the hope of completing step 1. But since they are sibling arrays, JSON_TABLE
produced two columns where total number of rows are 6 instead of 3. I do not know how to get past this.
Is there any simpler solution than this?
Thanks in advance.