Using JSON_EXTRACT() function in MySQL 8 (with examples)

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

Introduction

JSON (JavaScript Object Notation) has become a popular data interchange format due to its simplicity, lightweight nature, and wide support across different programming languages. MySQL, starting from version 5.7, introduced a set of native functions to handle JSON data. Among these, the JSON_EXTRACT() function is quintessential for retrieving data from JSON documents. Throughout this tutorial, we will explore the usage of JSON_EXTRACT() with a series of practical examples while discovering various features available starting in MySQL 8.

Understanding JSON in MySQL

Before delving into JSON_EXTRACT(), it’s essential to understand the JSON data type. In MySQL 8, a JSON column is a column with the JSON data type, capable of storing structured JSON objects. JSON columns allow you to store and query JSON document data within MySQL in an optimized and scalable fashion.

To begin with, ensure your MySQL server version is 8.0 or higher to take full advantage of these features. You can check your MySQL version using the command:

SELECT VERSION();

Basic Usage of JSON_EXTRACT()

The JSON_EXTRACT() function enables you to extract data from a JSON document. The function takes multiple arguments: the first argument is the JSON document, and the subsequent arguments are the paths to the elements you want to retrieve.

The basic syntax is:

JSON_EXTRACT(json_doc, path[, path] ...)

Example 1: Extracting a Single Element

Imagine a simple JSON object:

{ "name": "Jane", "age": 25 }

You can extract the value associated with the “name” key like this:

SET @json = '{ "name": "Jane", "age": 25 }';
SELECT JSON_EXTRACT(@json, '$.name');

The output will be:

"Jane"

Example 2: Extracting Multiple Elements

Extracting multiple elements at once is also possible:

SELECT JSON_EXTRACT(@json, '$.name', '$.age');

This returns:

["Jane", 25]

Using JSON Paths

JSON paths specify the location within a JSON document to extract. The path starts with a dollar symbol anchored to the root element and follows with object keys or array indices.

Example 3: Extracting Nested Elements

Assuming a nested JSON document:

{ "user": { "name": "Jane", "details": { "age": 25, "occupation": "engineer" } } }

To get Jane’s occupation, you’d use:

SET @json = '{ "user": { "name": "Jane", "details": { "age": 25, "occupation": "engineer" } } }';
SELECT JSON_EXTRACT(@json, '$.user.details.occupation');

Output will be:

"engineer"

Example 4: Extracting Elements from Arrays

Consider a JSON array:

{ "users": ["John", "Jane", "Doe"] }

To extract the second user’s name:

SET @json = '{ "users": ["John", "Jane", "Doe"] }';
SELECT JSON_EXTRACT(@json, '$.users[1]');

Output:

"Jane"

Working with JSON Tables

MySQL allows you to directly query JSON data stored in tables.

Example 5: JSON_EXTRACT() with Table Data

Assuming a table called “users” with a JSON column “attributes”:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    attributes JSON
);

Populate the table with a row:

INSERT INTO users(attributes) VALUES ('{ "name": "Jane", "age": 25, "interests": ["reading", "traveling"] }');

To select all users’ names from the “users” table:

SELECT JSON_EXTRACT(attributes, '$.name') FROM users;

Output would display the name of each user in the table.

Advanced JSON Path Expressions

You can leverage more advanced path expressions when retrieving JSON data.

Example 6: Using Wildcards in Paths

The wildcard operator (*) can be used to ignore array indices or object keys.

SELECT JSON_EXTRACT(@json, '$.users[*]');

Output will return all the users.

Example 7: Extracting Multiple Values with One Path

This capability is particularly useful in nested arrays or objects:

SET @json = '{ "team": { "members": [{ "name": "John" }, { "name": "Jane" }] } }';
SELECT JSON_EXTRACT(@json, '$.team.members[*].name');

And the output would be:

["John", "Jane"]

Conclusion

Through this tutorial, we’ve examined various ways the JSON_EXTRACT() function in MySQL 8 can be utilized to access and manipulate JSON data. We covered scenarios ranging from simple to complex, providing a comprehensive understanding of JSON operations within MySQL. Remember, while JSON provides flexibility in data representation, always design your schema and queries to be optimized for performance within MySQL’s capabilities.