Danilo Körber
Danilo Körber

Reputation: 910

JSON from SQL query with child level

I have a simple query in my database:

SELECT id, name FROM users FOR JSON AUTO, ROOT('users')

This returns the following JSON:

{
    "users": [
        {"id": "1", "name": "John"}
        {"id": "2", "name": "Mike"}
    ]
}

I want to have the return with the following format:

{
    "users": {
        "list": [
            {"id": "1", "name": "John"}
            {"id": "2", "name": "Mike"}
        ]
    }
}

Can I do this on SQL level by simply changing the query?

Upvotes: 2

Views: 681

Answers (1)

Zhorov
Zhorov

Reputation: 29943

You may try with this:

Table:

CREATE TABLE users (
   id varchar(1),
   [name] varchar(50)
)
INSERT INTO users
   (id, [name])
VALUES
   ('1', 'John'),
   ('2', 'Mike')

Statement:

SELECT users = (SELECT id, name FROM users FOR JSON AUTO, ROOT('list'))
FOR JSON PATH, WITHOUT_ARRAY_WRAPPER

Result:

{"users":{"list":[{"id":"1","name":"John"},{"id":"2","name":"Mike"}]}}

Upvotes: 5

Related Questions