Convert JSON data to split columns

I have the following DB structure:

ID Name Value 1 TV1 {"URL": "www.url.com", "Icon": "some_icon"} 2 TV2 {"URL": "www.url.com", "Icon": "some_icon", "Facebook": "Facebook_URL"} 3 TV3 {"URL": "www.url.com", "Icon": "some_icon", "Twitter": "Twitter_URL"} .......... 

I'm looking for a query with SQL Server 2012 native functions to extract JSON from a Value column and dynamically create columns, and I want to do this for a different number of columns without hard-coding the column names name , icon , twitter , facebook . So the result I'm looking for:

 ID Name URL Icon Facebook Twitter 1 TV1 www.url.com some_icon NULL NULL 2 TV2 www.url.com some_icon Facebook_URL NULL 3 TV3 www.url.com some_icon NULL Twitter_URL 

If this is not possible using native SQL Server mechanisms, perhaps PostgreSQL may do this or another RMDBS

PS. My question is not duplicated by Parse JSON in TSQL . I need to figure out a way to parse this heterogeneous json into strings

+5
source share
2 answers

In SQL Server 2016, you will be able to define the schema at query time when opening json:

 select id, name, url, icon, facebook, twitter from tab cross apply openjson(value) with (url nvarchar(100), icon varbinary, facebook nvarchar(100),twitter nvarchar(100)) 

Please note that you cannot have a dynamic return scheme - you need to specify which fields should be returned to TVF. Alternatively, you can use openjson without a WITH clause to dynamically return all key pairs: from a JSON object:

 select id, name, json.[key], json.value from tab cross apply openjson(value) as json 

In this version, OPENJSON will return rotational values. key: value pairs will not be returned as a column: cell - each key pair: value will be returned in separate rows:

 ID Name key value 1 TV1 URL www.url.com 1 TV1 Icon some_icon 2 TV2 URL www.url.com 2 TV2 Icon some_icon 2 TV3 Facebook Facebook_URL 3 TV3 URL www.url.com 3 TV3 Icon some_icon 3 TV3 Twitter Twitter_URL .... 

It will also be available in the Azure SQL database. In an earlier version, you will need to find or write a CLR TVF that parses JSON or uses extremely complex T-SQL. I can recommend JsonSelect and json4sql if you want to use existing CLR solutions. Another alternative for the old version of SQL Server is to use XML instead of JSON and use the nodes () function.

+6
source
0
source

Source: https://habr.com/ru/post/1235188/


All Articles