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

Convert two columns into key-value json object?


Instead of JSON functions of SQL Server 2016, I used string concatenation function string_agg in SQL Server 2017 as seen in following script

/*create table ProductAttributes (    product int,    attribute varchar(40),    value varchar(40))insert into ProductAttributes select 1, 'color', 'red'insert into ProductAttributes select 1, 'size', 'small'insert into ProductAttributes select 2, 'processor', 'intel'insert into ProductAttributes select 2, 'ram', '16'insert into ProductAttributes select 2, 'weight', '2'*/select     product, '{' + STRING_AGG( '"' + attribute + '":"' + STRING_ESCAPE(value,'json') + '"' ,',') + '}' as attributesfrom ProductAttributes group by product

Output is as follows for the two product entriesproduct attributes1 {"color":"red","size":"small"}2 {"processor":"intel","ram":"16","weight":"2"}

enter image description here

If you are using a previous version than SQL Server 2017, you can use string concatenation using SQL XML Path as follows

SELECT    product,  '{' + STUFF(    (    SELECT      ',' + '"' + attribute + '":"' + STRING_ESCAPE(value,'json') + '"'    FROM ProductAttributes a        where a.product = p.product    FOR XML PATH(''),TYPE    ).value('.','VARCHAR(MAX)'    ), 1, 1, ''  ) + '}' As attributesfrom ProductAttributes pgroup by product

Developers will get the same result

enter image description here

I've updated above SQL queries and used String_Escape() function @Eilert's comment