Convert SQL table to JSON array values

Devashish Parmar (BLR GSS) 86 Reputation points
2022-12-27T04:29:41.223+00:00

I have a table with the below format.

274136-image.png

I use the below query to convert to json:
select e.empId,
(select e1.age from employee e1 where e1.empId = e.empId for json auto) as age
from employee e for json auto

and below is the result.

[
{
"empId": 1,
"age": [
{
"age": 20
}
]
},
{
"empId": 2,
"age": [
{
"age": 17
}
]
},
{
"empId": 3,
"age": [
{
"age": 16
}
]
}
]

====================================

however my desired output should be as below. can you help me?
[
{
"empId": 1,
"age": [
20
]
},
{
"empId": 2,
"age": [
17
]
},
{
"empId": 3,
"age": [
16
]
}
]

i.e. 'age' should be come as an array of values and nota as an array of objects.

Developer technologies Transact-SQL
SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2022-12-27T06:32:52.31+00:00

    If empID is unique, then try something like this:

    select empId, json_query( concat('[', age, ']')) as age  
    from employee for json auto  
    

    In SQL 2022 you can use the new JSON_ARRAY function.


1 additional answer

Sort by: Most helpful
  1. Anonymous
    2022-12-27T08:15:26.023+00:00

    Hi @Devashish Parmar (BLR GSS)

    If your SQL version is before 2022, you can try the methods provided by Viorel-1. If your SQL version is 2022, you can give this query a try.

    select empId,json_array(Age) as age from employee for json auto;  
    

    Hope this helps with the problem you are experiencing.

    Best regards,
    Percy Tang

    ----------

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.