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?
1条答案
按热度按时间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 yourfor json path, without_array_wrapper
.Here's an example of how that could work.
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.