Skip to content
Advertisement

How to get in json a column that combine from two field in sql?

I have table with those columns in mssql:

 id, name, surname, age

How to combine name and surname into info when I get json from the sql:

select id, name, surname, age from table for json auto

What I get is:

[{ id, name, surname, age }]

And what I need is:

[{ id, info: { name, surname }, age }]

This is possible to do with mssql? if so, how can I do it in sql?

Advertisement

Answer

You need to use FOR JSON PATH to build the nested ouptut:

SELECT 
   id, 
   name AS 'info.name', 
   surname AS 'info.surname', 
   age 
FROM (VALUES
   (1, 'Name', 'Surname', 35)  
) t (id, name, surname, age)
FOR JSON PATH

Result:

[{"id":1,"info":{"name":"Name","surname":"Surname"},"age":35}]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement