Convert two columns into key-value json object?

后端 未结 1 1777
栀梦
栀梦 2021-02-08 02:57

Using FOR JSON AUTO or FOR JSON PATH on the following record set (which representing a product\'s attributes):

attribute | value
------         


        
相关标签:
1条回答
  • 2021-02-08 03:54

    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 attributes
    from ProductAttributes 
    group by product
    

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

    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 attributes
    from ProductAttributes p
    group by product
    

    Developers will get the same result

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

    0 讨论(0)
提交回复
热议问题