Quantcast
Channel: SQL Server - How to transform JSON to Relational database - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Nabil Shahid for SQL Server - How to transform JSON to Relational database

$
0
0

You can do this using openjson and json_value functions. Try the following:

Declare @json nvarchar(max),@table1Items nvarchar(max), @table2Items nvarchar(max)set @json='{"table1": {"Name": "table1","Items": [{"Id": 1,"FirstName": "John","LastName": "Wen","Country": "UK","PostCode": 1234,"Status": false,"Date": "2018-09-18T08:30:32.91"        }, {"Id": 2,"FirstName": "John1","LastName": "Wen1","Country": "UK1","PostCode": 12341,"Status": true,"Date": "2018-09-15T08:30:32.91"        }]    },"table2": {"Name": "table2","Items": [{"Id": 1,"Name": "leo","StudentId": 102,"CreatedDate": "2018-09-18","Location": "USA"        }]    }}'set @table1Items=(select value from OpenJSON((select value from OpenJSON(@Json) where [key]='table1')) where [key]='Items') set @table2Items=(select value from OpenJSON((select value from OpenJSON(@Json) where [key]='table2')) where [key]='Items') --select for table 1select JSON_VALUE(val,'$.Id') as ID, JSON_VALUE(val,'$.FirstName') as FirstName,JSON_VALUE(val,'$.LastName') as LastName,JSON_VALUE(val,'$.Country') as Country,JSON_VALUE(val,'$.PostCode') as PostCode,JSON_VALUE(val,'$.Status') as Status,JSON_VALUE(val,'$.Date') as Datefrom(select value as val from openJSON(@table1Items)) AS Table1JSON--select for table 1select JSON_VALUE(val,'$.Id') as ID, JSON_VALUE(val,'$.Name') as FirstName,JSON_VALUE(val,'$.StudentId') as LastName,JSON_VALUE(val,'$.CreatedDate') as Country,JSON_VALUE(val,'$.Location') as PostCodefrom(select value as val from openJSON(@table2Items)) AS Table2JSON

It is working exactly as you wanted. At the end, the two select statements return the tables as you mentioned. Just add them to your desired table using insert into select. I have also tried adding another object to table1 array and verified that it is working fine i.e. returning two rows for two objects. Hope this helps


Viewing all articles
Browse latest Browse all 4

Trending Articles





<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>