2

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?

1 Answer 1

5

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"}]}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.