Working with JSON_ARRAY() function in MySQL 8

Updated: January 26, 2024 By: Guest Contributor Post a comment

Introduction

Working with JSON data in MySQL has become increasingly important as the use of JSON has exploded in web, mobile, and cloud applications. MySQL introduced a set of native JSON functions in MySQL 5.7 and further enhanced them in MySQL 8.0. Among these, the JSON_ARRAY() function is one of the most useful tools. This guide will provide a comprehensive tutorial on using the JSON_ARRAY() function in MySQL 8, including code examples that range from basic to advanced.

A Glance at JSON_ARRAY() Function

The JSON_ARRAY() function in MySQL is used to create a JSON array from a list of arguments. JSON arrays are an ordered list of values which can be elements of various types (numbers, strings, boolean values, objects, or arrays). This function can be very useful when you need to generate a JSON array dynamically from the queried data in your database.

SELECT JSON_ARRAY('value1', 'value2', 3, NULL, true);

Output: ["value1", "value2", 3, null, true]

Creating Basic JSON Arrays

Let’s start with some basic examples of the JSON_ARRAY() function.

SELECT JSON_ARRAY('Apple', 'Banana', 'Cherry');

Output: ["Apple", "Banana", "Cherry"]

You can also use numbers and mixing data types in an array.

SELECT JSON_ARRAY(1, 'two', 3.14);

Output: [1, "two", 3.14]

Nesting JSON Arrays

You can nest arrays within arrays using the JSON_ARRAY() function. This can be crucial when you want to create a complex JSON structure directly from a database query.

SELECT JSON_ARRAY('Fruits', JSON_ARRAY('Apple', 'Banana'), 'Vegetables', JSON_ARRAY('Carrot', 'Lettuce'));

Output: ["Fruits", ["Apple", "Banana"], "Vegetables", ["Carrot", "Lettuce"]]

Combining JSON_ARRAY() with Other JSON Functions

MySQL 8 gives us the ability to combine JSON_ARRAY() with other JSON functions to manipulate and create complex JSON structures.

Here we will use the JSON_OBJECT() function within JSON_ARRAY() to create an array of JSON objects:

SELECT JSON_ARRAY(
    JSON_OBJECT('type', 'Fruit', 'name', 'Apple'),
    JSON_OBJECT('type', 'Vegetable', 'name', 'Carrot')
);

Output: [{"type": "Fruit", "name": "Apple"}, {"type": "Vegetable", "name": "Carrot"}]

Extracting Data from JSON Arrays

After you’ve created JSON arrays, you often need to extract data from them. Use the JSON_EXTRACT() function to retrieve the elements of a JSON array. The array elements can be accessed by zero-based index in the path expression.

SET @fruits = JSON_ARRAY('Apple', 'Banana', 'Cherry');
SELECT JSON_EXTRACT(@fruits, '$[1]');

Output: "Banana"

Modifying JSON Arrays

With MySQL’s JSON functions, you can also modify existing JSON arrays. The JSON_SET(), JSON_INSERT(), and JSON_REPLACE() functions allow you to update JSON arrays.

SET @fruits = JSON_ARRAY('Apple', 'Banana', 'Cherry');
SET @fruits = JSON_INSERT(@fruits, '$[1]', 'Orange'); -- Inserts at position 1
SET @fruits = JSON_SET(@fruits, '$[1]', 'Kiwi');    -- Updates value at position 1
SELECT @fruits;

Output: ["Apple", "Kiwi", "Orange", "Cherry"]

Advanced Use Cases

More advanced use cases involve combining JSON_ARRAY() with aggregate functions or generating JSON array representations of subqueries.

To illustrate, assume we have a table sales with the columns product and quantity. We can create a JSON array of objects representing total quantities sold for each product:

SELECT JSON_ARRAYAGG(
    JSON_OBJECT('product', product, 'quantity', SUM(quantity))
)
FROM sales
GROUP BY product;

This aggregates the data in a way that each product and its total quantity sold is a separate JSON object within the array.

Combining JSON_ARRAY() With Other SQL Features

A truly powerful feature of MySQL 8 is the ability to integrate JSON functions with other SQL queries and commands. This allows for dynamic and robust data representation and storage within your relational database.

Here’s how you can use a subquery in combination with JSON_ARRAY():

SELECT JSON_ARRAY(
    (SELECT GROUP_CONCAT(user_name) FROM users WHERE active = 1)
);

In this query, we’re getting an array of active user names fetched from the users table.

Conclusion

In conclusion, the JSON_ARRAY() function is a versatile toolkit which permits direct manipulation and generation of JSON array data within MySQL. By integrating it with other MySQL functions and SQL features, we can effectively handle complex data structures in a streamlined and efficient manner, right within our database.