sql server - Convert two columns into key-value json object? -


using for json auto or for json path on following record set (which representing product's attributes):

attribute | value ----------------- color     | red size      | small 

will produce:

[{"attribute":"color","value":"red"},{"attribute":"size","value":"small"}] 

is there way produce following instead:

{"color":"red","size":"small"} 

note every product attribute different others; record set different every product. pivoting not option needs dynamic sql! seems need function able cross products table produce example product catalog.

instead of json functions of sql server 2016, used string concatenation function string_agg in sql server 2017 seen in following script

/*create table productattributes (     product int,     attribute varchar(40),     value varchar(40) ) insert productattributes select 1, 'color', 'red' insert productattributes select 1, 'size', 'small' insert productattributes select 2, 'processor', 'intel' insert productattributes select 2, 'ram', '16' insert productattributes select 2, 'weight', '2'*/  select      product, '{' + string_agg( '"' + attribute + '":"' + value + '"' ,',') + '}' attributes productattributes  group product 

output follows 2 product entries product attributes 1 {"color":"red","size":"small"} 2 {"processor":"intel","ram":"16","weight":"2"}

enter image description here

if using previous version sql server 2017, can use string concatenation using sql xml path follows

select     product,   '{' + stuff(     (     select       ',' + '"' + attribute + '":"' + value + '"'     productattributes         a.product = p.product     xml path(''),type     ).value('.','varchar(max)'     ), 1, 1, ''   ) + '}' attributes productattributes p group product 

developers same result

enter image description here


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -