Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why SQL returns an Array instead of an Object?

I'm using SQL SERVER 2016 JSON result, but I don't know why it converts everything to array, e.g. if I execute the following query it returns an array instead of an object:

SELECT 1 AS One,2 AS Two,3 AS Three
FOR JSON PATH

The result is:

[{"One":1,"Two":2,"Three":3}]

But I would like it to return:

{"One":1,"Two":2,"Three":3}

Also I tested this query, but the result was the same, again an array:

SELECT TOP 1 1 AS One,2 AS Two,3 AS Three
FOR JSON PATH
like image 710
Saman Gholami Avatar asked Oct 04 '16 10:10

Saman Gholami


People also ask

What does array mean in SQL?

An array is an ordered set of elements of a single built-in data type. An array can have an associated user-defined array type, or it can be the result of an SQL operation that returns an array value without an associated user-defined array type.

Should I use array in SQL?

Arrays are a first class data type in the SQL standard, and generally allow for a simpler schema and more efficient queries. Arrays, in general, are a great data type.

Is there an array data type in SQL Server?

The SQL Array Library uses the SQL Server binary data-type to store arrays. SQL Server supports to ways of storing binary data. If the structure size is under 8000 bytes it is stored in-page and the corresponding SQL data-type is varbinary(n) where n ≤ 8000.

Can SQL store arrays?

Conclusion. As you can see, SQL Server does not include arrays. But we can use table variables, temporary tables or the STRING_SPLIT function. However, the STRING_SPLIT function is new and can be used only on SQL Server 2016 or later versions.


1 Answers

You just need the WITHOUT_ARRAY_WRAPPER option:

SELECT 1 AS One,2 AS Two,3 AS Three
FOR JSON PATH ,WITHOUT_ARRAY_WRAPPER; 
like image 88
S.Karras Avatar answered Jan 06 '23 20:01

S.Karras