mysql
  1. mysql-json

JSON - MySQL

In MySQL, JSON is a data format that can be stored and manipulated using the JSON functions. In this tutorial, we'll discuss the syntax, example, output, and use of JSON in MySQL.

Syntax

In MySQL, you can define a column to store JSON data using the JSON data type. You can also use the JSON functions to manipulate JSON data. Here's an example of defining a JSON column:

CREATE TABLE example (
   id INT PRIMARY KEY,
   data JSON
);

Example

Let's say we want to store information about a user in a JSON column. Here's how we can insert data into the JSON column:

INSERT INTO example (id, data)
VALUES (1, '{"name": "John", "age": 30}');

Now, we can retrieve the JSON data using the JSON_EXTRACT function:

SELECT id, JSON_EXTRACT(data, '$.name')
FROM example
WHERE id = 1;

This will return the name "John".

Output

When we run the example code above, the output will be:

id   name
1    John

This is because we used the JSON_EXTRACT function to extract the name from the JSON data.

Explanation

In the example above, we defined a table with a JSON column and inserted JSON data into it. We then used the JSON_EXTRACT function to retrieve a specific value from the JSON data.

Use

JSON in MySQL can be used to store and manipulate JSON data in a database. This is useful when working with languages or frameworks that use JSON natively, such as JavaScript.

Important Points

  • MySQL provides several functions for manipulating JSON data, including JSON_EXTRACT, JSON_ARRAY, and JSON_OBJECT.
  • JSON data in MySQL must be well-formed, or else it will result in an error.
  • JSON data in MySQL can be queried using the -> operator, e.g. WHERE data->>'$.name' = 'John' would return all rows where the "name" field in the JSON object is "John".

Summary

In this tutorial, we discussed the syntax, example, output, and use of JSON in MySQL. With this knowledge, you can now store and manipulate JSON data in a MySQL database using the JSON functions provided by MySQL.

Published on: