In SQL server, how do I output one JSON dictionary? [duplicate]

vmpqdwk3  于 5个月前  发布在  SQL Server
关注(0)|答案(1)|浏览(47)

This question already has answers here:

SQL Server nest JSON output (1 answer)
Customize "for json auto" to get customized result (2 answers)

How to build JSON with selected fields from JSON columns in SQL Server keeping fields type (3 answers)
Closed last month.

Let's say I have a table with three columns, docid , key and value . I would like to get one dictionary for a given docid .

I tried this:

select key, value from mytable where docid=456 for json path

But I get this:

[{"key":"key1", "value":"value1"}, {"key":"key2","value":"value2"},...]

I would like this:

{"key1":"value1", "key2":"value2",...}

json_object function does not allow aggregating Is there a way to accomplish this without defining functions?

6ojccjat

6ojccjat1#

You're going to have to perform a dynamic pivot on your data first; pivoting on all the distinct values in your key column, and projecting them as distinct columns. And then doing your for json path, without_array_wrapper .

Here's an example of how that could work.

drop table if exists #data
create table #data
(
    K varchar(30),
    V varchar(30)
)

insert into #data
select 'key1', 'value1' union all
select 'key2', 'value2' union all
select 'key3', 'value3' 

declare 
    @Columns nvarchar(max),
    @SQL nvarchar(max),
    @JSON nvarchar(max)

select @Columns = string_agg(quotename(K), ',')
from #data

select @SQL = 
concat
('
    select @JSON = 
    (
        select ' , @Columns, '
        from #data d
        pivot (max(V) for K in (', @Columns, ')) p
        for json path, without_array_wrapper
    )
')

exec sp_executesql 
    @sql,
    N'@JSON nvarchar(max) output',
    @Json output

select @JSON

This outputs

{"key1":"value1","key2":"value2","key3":"value3"}

Here's another SO article on dynamic pivots . The concept is the same, you're just wrapping the results in a for json call.

相关问题