2

Using MySQL Server, I have a simple SELECT statement and need to return Json. All I've found so far is the JSON_OBJECT syntax like this:

SELECT JSON_OBJECT( 
'Id', Id, 
'Name', Name, 
'State', State)
FROM ACustomer;

Which returns this:

{"Id": 1, "Name": "Ajax", "State": "WA"}
{"Id": 2, "Name": "Bluebell", "State": "TX"}
{"Id": 3, "Name": "Cornpops", "State": "CA"}

but it needs to return valid Json like this:

[
{"Id": 1, "Name": "Ajax", "State": "WA"},
{"Id": 2, "Name": "Bluebell", "State": "TX"},
{"Id": 3, "Name": "Cornpops", "State": "CA"}
]

In SQL Server we add this to the end of the select statement and everything is formatted perfectly:

FOR JSON PATH;

Is there a way to do this in MySQL?

Thank you.

1 Answer 1

3

You need to include the JSON_ARRAYAGG syntax like this:

SELECT JSON_ARRAYAGG(JSON_OBJECT( 
'Id', Id, 
'Name', Name, 
'State', State))
FROM ACustomer;

I know, this is not documented well and you would think this would be much more common.

Hope this helps.

Sign up to request clarification or add additional context in comments.

1 Comment

You should note that the OP query returns multiple rows -- one for each JSON object -- while this solution returns a single row with all objects assembled into a single JSON array. Both queries are correct, depending on the result that is needed.

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.