skip to Main Content

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


  1. Just one option using string_agg() and OPENJSON(). Note this is simple/non-nested approach.

    Example

    declare @jsonVar nvarchar(max) = N'{"key1":"value1","key2":"value2"}';
    
    Select '<root>' + string_agg( concat('<',[key],'>',value,'</',[key],'>'),'' )  + '</root>'
     From  OPENJSON(@jsonVar)
    

    Results

    <root>
       <key1>value1</key1>
       <key2>value2</key2>
    </root>
    
    Login or Signup to reply.
  2. 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

    DECLARE @jsonVar NVARCHAR(MAX) = N'{"key1":"value1","key2":"value2"}';
    
    ;WITH rs AS
    (
        SELECT *
        FROM  OPENJSON(@jsonVar)
    )
    SELECT * 
    FROM rs
    FOR XML PATH('row'), TYPE, ROOT('root');
    

    Output

    <root>
      <row>
        <key>key1</key>
        <value>value1</value>
        <type>1</type>
      </row>
      <row>
        <key>key2</key>
        <value>value2</value>
        <type>1</type>
      </row>
    </root>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search