0

I want that MySQL will return a result set in a form of JSON array.

A worked query:

SELECT CONCAT(
    '[',
        GROUP_CONCAT(
            JSON_OBJECT(
                'ProductId', tblproducts.ProductId,
                'ProductName', tblproducts.ProductName
            )
        ),
    ']') As Products
FROM tblproducts;

This query returns the following JSON array:

[
    {
        "ProductId": "1",
        "ProductName": "Milk"
    },
    {
        "ProductId": "2",
        "ProductName": "Bread"
    }
]

Although this code works, I have a strong feeling that building a JSON array with GROUP_CONCAT and CONCAT is kind of workaround. If to use a JSON_ARRAY, a result set will consist of JSON arrays for each JSON_OBJECT.

Is there any native way to get a single JSON array with all JSON_OBJECT in the result set?

1 Answer 1

1

JSON_ARRAYAGG() could be what you're looking for.

SELECT JSON_ARRAYAGG(
    JSON_OBJECT(
        'ProductId', tblproducts.ProductId,
        'ProductName', tblproducts.ProductName
    )
) FROM tblproducts;

Here's an example: https://www.db-fiddle.com/f/uQ9UC7MDZM4gncNjViTsKw/0

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.