Table of Contents
Combined with the two acquisition methods introduced earlier, you can obtain the nested data in json data
- Obtain JSON data of multiple paths
Will combine the data of multiple paths into an array and return
will combine the data of multiple paths into an array and return
If the first parameter is not JSON type data, return error
The JSON_EXTRACT function is usually used when you want to obtain a specific data in JSON or use it as a judgment condition
Home Database Mysql Tutorial How to use json_extract in mysql

How to use json_extract in mysql

May 31, 2023 pm 04:58 PM
mysql json_extract

    ##1. Foreword

    mysql5.7 version begins to support JSON type fields

    json_extract can be completely abbreviated as
    -> json_unquote(json_extract()) can be completely abbreviated as
    ->>Most of the following introductions will use the abbreviation

    2. Create Example table

    CREATE TABLE `test_json` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `content` json DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4;
    Copy after login
    # 插入两条测试用的记录
    INSERT INTO `test_json` (`content`) VALUES ('{\"name\":\"tom\",\"age\":18,\"score\":[100,90,87],\"address\":{\"province\":\"湖南\",\"city\":\"长沙\"}}');
    INSERT INTO `test_json` (`content`) VALUES ('[1, "apple", "red", {"age": 18, "name": "tom"}]');
    Copy after login

    idcontent1{"age": 18, "name": "tom", "score": [100, 90, 87], "address": {"city": "Changsha", "province": "Hunan"}} 2[1, “apple”, “red”, {“age”: 18, “name”: “tom”}]
    3. Basic syntax

    - Obtain the value corresponding to a key in the JSON object

    • In the json_extract function, the first One parameter content represents json data, and the second parameter is the json path, where $ represents the json data itself, and $.name represents obtaining the value with the key name in json

    • You can use -> expression instead of json_extract

    • If the obtained val itself is a string, then the obtained val will be wrapped in quotation marks, such as "tom", this kind of data is When parsed into a program object, it may be escaped as \"tom\". In order to solve this problem, you can wrap another layer of json_unquote function outside, or use ->> instead of ->

    content:

    {" age”: 18, “name”: “tom”, “score”: [100, 90, 87], “address”: {“city”: “Changsha”, “province”: “Hunan”}}

    # 得到"tom"
    select json_extract(content,'$.name') from test_json where id = 1;
    # 简写方式:字段名->表达式等价于json_extract(字段名,表达式)
    select content->'$.name' from test_json where id = 1;
    # 结果:
    +--------------------------------+
    | json_extract(content,'$.name') |
    +--------------------------------+
    | "tom"                          |
    +--------------------------------+
    +-------------------+
    | content->'$.name' |
    +-------------------+
    | "tom"             |
    +-------------------+
    
    # 解除双引号,得到tom
    select json_unquote(json_extract(content,'$.name')) from test_json where id = 1;
    # 简写方式:字段名->>表达式等价于json_unquote(json_extract(字段名,表达式))
    select content->>'$.name' from test_json where id = 1;
    # 结果:
    +----------------------------------------------+
    | json_unquote(json_extract(content,'$.name')) |
    +----------------------------------------------+
    | tom                                          |
    +----------------------------------------------+
    +--------------------+
    | content->>'$.name' |
    +--------------------+
    | tom                |
    +--------------------+
    Copy after login
    - Get an element in the JSON array

    • In the json_extract function, the first parameter content represents json data, and the second parameter is the json path, where $ Represents the json data itself, $[i] indicates obtaining the element with index i of the json array (the index starts from 0)

    • is the same as obtaining key-val, if the obtained element is For strings, the default method will also get characters enclosed in double quotes, causing the program to escape. The method is also to use the json_unquote function, or use ->> instead of ->

    ##content:
    [1, “apple”, “red”, {“age”: 18, “name”: “tom”}]


    # 得到"apple"
    select json_extract(content,'$[1]') from test_json where id = 2;
    # 简写,效果同上
    select content->'$[1]' from test_json where id = 2;
    # 结果:
    +------------------------------+
    | json_extract(content,'$[1]') |
    +------------------------------+
    | "apple"                      |
    +------------------------------+
    +-----------------+
    | content->'$[1]' |
    +-----------------+
    | "apple"         |
    +-----------------+
    
    # 解除双引号,得到apple 
    select json_unquote(json_extract(content,'$[1]')) from test_json where id = 2;
    # 简写,效果同上
    select content->>'$[1]' from test_json where id = 2;
    # 结果:
    +--------------------------------------------+
    | json_unquote(json_extract(content,'$[1]')) |
    +--------------------------------------------+
    | apple                                      |
    +--------------------------------------------+
    +------------------+
    | content->>'$[1]' |
    +------------------+
    | apple            |
    +------------------+
    Copy after login

    - Get JSON Nested data

    Combined with the two acquisition methods introduced earlier, you can obtain the nested data in json data

    content: id=1
    {"age": 18 , “name”: “tom”, “score”: [100, 90, 87], “address”: {“city”: “Changsha”, “province”: “Hunan”}}

    content: id= 2
    [1, “apple”, “red”, {“age”: 18, “name”: “tom”}]

    # 得到:87
    select content->'$.score[2]' from test_json where id = 1;
    # 结果:
    +-----------------------+
    | content->'$.score[2]' |
    +-----------------------+
    | 87                    |
    +-----------------------+
    
    # 得到:18
    select content->'$[3].age' from test_json where id = 2;
    # 结果:
    +---------------------+
    | content->'$[3].age' |
    +---------------------+
    | 18                  |
    +---------------------+
    Copy after login

    4. Getting better

    - Obtain JSON data of multiple paths

    Will combine the data of multiple paths into an array and return

    content: id=1
    {"age": 18, “name”: “tom”, “score”: [100, 90, 87], “address”: {“city”: “Changsha”, “province”: “Hunan”}}


    select json_extract(content,'$.age','$.score') from test_json where id = 1;
    # 结果:
    +-----------------------------------------+
    | json_extract(content,'$.age','$.score') |
    +-----------------------------------------+
    | [18, [100, 90, 87]]                     |
    +-----------------------------------------+
    
    select json_extract(content,'$.name','$.address.province','$.address.city') from test_json where id = 1;
    # 结果:
    +----------------------------------------------------------------------+
    | json_extract(content,'$.name','$.address.province','$.address.city') |
    +----------------------------------------------------------------------+
    | ["tom", "湖南", "长沙"]                                              |
    +----------------------------------------------------------------------+
    Copy after login

    - The use of path expression *

    will combine the data of multiple paths into an array and return

    # 先插入一条用于测试的数据
    INSERT INTO `test_json` (`id`,`content`) VALUES(3,'{"name":"tom","address":{"name":"中央公园","city":"长沙"},"class":{"id":3,"name":"一年三班"},"friend":[{"age":20,"name":"marry"},{"age":21,"name":"Bob"}]}')
    Copy after login

    content: id=3
    {“name ": "tom", "class": {"id": 3, "name": "Class Three a Year"}, "friend": [{"age": 20, "name": "marry"}, {"age": 21, "name": "Bob"}], "address": {"city": "Changsha", "name": "Central Park"}}


    # 获取所有二级嵌套中key=name的值
    # 由于friend的二级嵌套是一个数组,所以.name获取不到其中的所有name值
    select content->'$.*.name' from test_json where id = 3;
    +----------------------------------+
    | content->'$.*.name'              |
    +----------------------------------+
    | ["一年三班", "中央公园"]         |
    +----------------------------------+```
    
    # 获取所有key为name值的数据,包括任何嵌套内的name
    select content->'$**.name' from test_json where id = 3;
    +---------------------------------------------------------+
    | content->'$**.name'                                     |
    +---------------------------------------------------------+
    | ["tom", "一年三班", "marry", "Bob", "中央公园"]         |
    +---------------------------------------------------------+
    
    # 获取数组中所有的name值
    select content->'$.friend[*].name' from test_json where id = 3;
    +-----------------------------+
    | content->'$.friend[*].name' |
    +-----------------------------+
    | ["marry", "Bob"]            |
    +-----------------------------+
    Copy after login

    - Return NULL value

    content: id=1
    {"age": 18, "name": "tom", "score": [100, 90, 87], "address" ": {"city": "Changsha", "province": "Hunan"}}


    The JSON path you are looking for does not exist
    # age路径不存在,返回NULL
    # 若有多个路径,只要有一个路径存在则不会返回NULL
    select json_extract(content,'$.price') from test_json where id = 1;
    +---------------------------------+
    | json_extract(content,'$.price') |
    +---------------------------------+
    | NULL                            |
    +---------------------------------+
    Copy after login

    There are NULL

    in the path
    # 存在任意路径为NULL则返回NULL
    select json_extract(content,'$.age',NULL) from test_json where id = 1;
    +------------------------------------+
    | json_extract(content,'$.age',NULL) |
    +------------------------------------+
    | NULL                               |
    +------------------------------------+
    Copy after login

    - Return error

    If the first parameter is not JSON type data, return error

    select json_extract('{1,2]',$[0])
    Copy after login

    If the path expression is not standardized, return error

    select content->'$age' from test_json where id = 1;
    # 结果:
    ERROR 3143 (42000): Invalid JSON path expression. The error is around character position 1.
    Copy after login

    5. Usage scenarios

    The JSON_EXTRACT function is usually used when you want to obtain a specific data in JSON or use it as a judgment condition

    The above is the detailed content of How to use json_extract in mysql. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

    MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

    MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

    MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

    How to connect to the database of apache How to connect to the database of apache Apr 13, 2025 pm 01:03 PM

    Apache connects to a database requires the following steps: Install the database driver. Configure the web.xml file to create a connection pool. Create a JDBC data source and specify the connection settings. Use the JDBC API to access the database from Java code, including getting connections, creating statements, binding parameters, executing queries or updates, and processing results.

    Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

    MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

    How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

    The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

    MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

    The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

    Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

    Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

    How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

    The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

    See all articles