I have a variable which contains a single JSON object like
declare @jsonVar nvarchar(max) = N'{"key1":"value1","key2":"value2"}';
I need to convert it to XML and get something like this (or without ‘root’ at all)
<root>
<key1>value1</key1>
<key2>value2</key2>
</root>
The solution should be universal and should not list JSON keys, since they can vary.
Thank you.
2
Answers
Just one option using
string_agg()
andOPENJSON()
. Note this is simple/non-nested approach.Example
Results
It is not a good idea to add a running number to the XML element names, i.e.
<key1>
,<key2>
, etc.Check it out a different more palatable XML structure.
And as @PanagiotisKanavos pointed out, it will protect you from having values that contain invalid characters for the XML element names, eg spaces or slashes in the keys, angle brackets, and the like.
SQL
Output