World Database
We will be using the good old World database that MySQL has used for years in documentation, examples, and in the classroom. Starting with a simple query we will build up to something more complex.
SELECT Name, District, Population FROM City;
This will output the data from the table in a tabular format.
'Kabul', 'Kabol', '1780000' 'Qandahar', 'Qandahar', '237500'
Array or Object?
We have two options for composing JSON data: JSON_ARRAY and JSON_OBJECT.Of the two, you will find JSON_ARRAY the least fussy. It will JSON-ize your data very easily. It takes a list of values or an empty list and returns a JSON array.
We add this function to our example query and it becomes SELECT JSON_ARRAY(Name, District, Population) FROM City;
And the output looks like:
'[\"Kabul\", \"Kabol\", 1780000]' '[\"Qandahar\", \"Qandahar\", 237500]' ...
JSON_OBJECT wants key/value pairs and will complain if the key name is NULL or you have an odd number of objects. If we try SELECT JSON_OBJECT(Name, District, Population) FROM City; we will get Error Code: 1582. Incorrect parameter count in the call to native function 'JSON_OBJECT'. This fuctions sees the odd number of arguments as a 'key' and the evens as the 'value' in key/value pairs and therefore we should not have an odd number of arguments. We could stick in a dummy literal string into the select but odds are that we want the three fields specified but need to turn them into key/value pairs. So lets add 'keys' and let the database supply the values.
SELECT JSON_OBJECT('City', Name, 'Dist', District, 'Pop', Population) FROM City;,
And the output looks like:
'{\"Pop\": 1780000, \"City\": \"Kabul\", \"Dist\": \"Kabol\"}' '{\"Pop\": 237500, \"City\": \"Qandahar\", \"Dist\": \"Qandahar\"}' ...