Retrieve JSON elements from a MYSQL database where the JSON data is present

In my database, I have a table orders which contains orders.items in JSON format.

An example of the orders.items cell looks like this:



    {
    "10": {
        "name": "item 1",
        "step": "1",
        "price": "140",
        "amount": "4",
        "category": "9"
    },
    "24": {
        "name": "item 2",
        "step": "1",
        "price": "6.2",
        "amount": "1",
        "category": "5"
    },
    "35": {
        "name": "item 3",
        "step": "1",
        "price": "2.9",
        "amount": "3",
        "category": "1"
    },
    "37": {
        "name": "item 4",
        "step": "1",
        "price": "3.9",
        "amount": "2",
        "category": "9"
    }
    }


I need to extract only items that belong to a specific category.

The expected result for extracting items with category "9" should look like this:



    {
    "10": {
        "name": "item 1",
        "step": "1",
        "price": "140",
        "amount": "4",
        "category": "9"
    },
    "37": {
        "name": "item 4",
        "step": "1",
        "price": "3.9",
        "amount": "2",
        "category": "9"
    }
    }


So far, I was able to retrieve all orders.items cells where there is an item with category = "9".


SELECT
  `id`,
  JSON_EXTRACT(`orders`.`items`,
  '$')
FROM
  `orders`
WHERE
  JSON_CONTAINS(
    JSON_EXTRACT(`orders`.`items`,
    '$.*.category'),
    '"9"'
  )

Answer №1

lib_mysqludf_preg was utilized as a user-defined function (UDF):

mysql> DROP TABLE IF EXISTS `orders`;
Query OK, 0 rows affected (0.00 sec)

[Other MySQL commands and queries]

mysql> SELECT `id`, `items`
    -> FROM `orders`;
+----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| id | items                                                                                                                                                                                                                                                                                                                                                        |
+----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
|  1 | {"10": {"name": "item 1", "step": "1", "price": "140", "amount": "4", "category": "9"}, "24": {"name": "item 2", "step": "1", "price": "6.2", "amount": "1", "category": "5"}, "35": {"name": "item 3", "step": "1", "price": "2.9", "amount": "3", "category": "1"}, "37": {"name": "item 4", "step": "1", "price": "3.9", "amount": "2", "category": "9"}} |
|  2 | {"10": {"name": "item 1", "step": "1", "price": "141", "amount": "4", "category": "9"}}                                                                                                                                                                                                                                                                      |
|  3 | {"10": {"name": "item 1", "step": "1", "price": "141", "amount": "4", "category": "8"}}                                                                                                                                                                                                                                                                      |
+----+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

[Additional MySQL commands and queries]

mysql> DEALLOCATE PREPARE `stmt`;
Query OK, 0 rows affected (0.00 sec)

MariaDB provides built-in function REGEXP_REPLACE for similar functionality, you can test it on dbfiddle.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Eliminate the page base from WordPress URLs to enhance code customization

I came across an interesting thread that caught my attention: Removing category & tag base from WordPress URL - no plugin needed After trying out various solutions mentioned in the thread, such as modifying the functions.php file and using the wp-no-categ ...

When attempting to submit, the jQuery validations fail to function accordingly

I have created an HTML form along with jQuery for validation purposes. However, upon clicking the submit button, nothing seems to be happening. I am unsure if my form is properly connecting with the jQuery file or not. Can someone please review my code and ...

Information vanishes as the element undergoes modifications

I am currently working with a JSON file that contains information about various events, which I am displaying on a calendar. Whenever an event is scheduled for a particular day, I dynamically add a div element to indicate the presence of an event on the c ...

Checking if an array exists after parsing JSON using jQuery

I am working on a solution to automatically submit form fields after triggering the onchange event. After making some changes, the JSON response I receive appears in this format: { "data": [ { "name":"p_data1,KEY=1", "value":"2", "error":"no error" } ] } ...

Exploring the depths of nested JSON structures with ReactJS

I'm facing an issue while trying to access the nested data from my JSON. The error message that keeps popping up is "Cannot read property 'map' of undefined". I've searched for solutions and watched tutorials, but the problem persists. ...

The issue of jQuery POST methods consistently failing

I have set up a Node.js server using Express with a fairly straightforward configuration: var express = require('express'); var app = express(); app.configure(function() { app.use(express.urlencoded()); app.use(express.json()); app ...

Identifying and Validating Icon Files in PHP: A Guide to Detecting *.ico File Integrity

Is there a way to determine if *.ico images are recognized as valid icons in PHP code? I attempted to use the getimagesize function, but unfortunately it does not have support for ICO files. ...

Struggling with retrieving information from a local JSON file using React

I am encountering an issue in my React project while trying to access a local JSON file located in the src folder using fetch. [ { "id": 1, "field1": "some data", "field2": 63, "field3": ...

What is the proper way to include an ID in a datepicker field along with the selected

Here is the layout of the table structure, displaying only specific dates that are available in the date picker. When a user clicks on one of these available dates, I need to retrieve the corresponding price. Table Structure https://i.stack.imgur.com/bJr ...

Obtain an array from an Ajax request using jQuery Datatables

I have integrated the jQuery DataTables Select plugin into my project to enable the selection of multiple rows from a table and storing their data inside an array. Subsequently, I am attempting to make an Ajax Request to pass this array to another PHP file ...

How can I prevent opening duplicate tabs of the same website simultaneously?

Is there a way to prevent users from accessing the same website page from multiple tabs? Could this be accomplished using JavaScript? ...

Converting a list of base classes to JSON using Unity's JSONUtility

I am working with a BaseClass and several subclasses. In my code, I have a List<BaseClass> that holds instances of these subclasses. When I try to convert this list to JSON using JSONUtility.ToJson(List<BaseClass>), it only includes propertie ...

The issue encountered is when the Ruby posting field appears as an empty JSON object during the

Update: Below are the details of the POST data and ruby log that I have been examining: Ruby log: Started PUT "/things/1" for 127.0.0.1 at 2014-10-28 10:54:32 -0700 Processing by ThingController#update as JSON Parameters: { "name"=>"Name", "im ...

Effortlessly retrieve related data when serializing in Laravel Eloquent using toArray and toJson

I have been using this method to automatically fetch user and replies when serializing my object to JSON. However, I am not sure if overriding the toArray method is the correct approach for this. What do you think? <?php class Post extends Eloquent ...

Press on any two table cells to select their content, highlight it, and save their values in variables

I have a table retrieved from a database that looks like this (the number of rows may vary): |Player 1|Player 2| ------------------- |Danny |Danny | |John |John | |Mary |Mary | My goal is to select one name from each Player column and sto ...

The JSON deserialization results in a null value being returned

When sending a JSON object with AJAX formData to my Controller, I am facing an issue where it always returns null when trying to deserialize it to an object. While I can convert it to dynamic, I struggle to convert the dynamic type to the Category class. ...

Tips for extracting the page name from a URL without the file extension

Is there a way to retrieve information from the URL page name? For instance, consider the following URL: www.example.com/blabla/12345.php I am interested in creating a variable $id that captures the value 12345 (without the .php extension) Also, why does ...

Inserting information into a MySQL database using a dynamic jQuery-generated form

i'm attempting to input data into MySQL from a dynamic form utilizing jQuery. Just to clarify, I am working with Twitter Bootstrap. Currently, I managed to insert "rows" but without any data. The most helpful resources I came across are located here f ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

How can I retrieve the value of a particular key within a string using Swift?

After receiving a server response, I'm trying to access specific data within it. ( { agreementId = "token.virtual.4321"; city = AMSTERDAM; displayCommonName = "bunch-of-alphanumeric"; displaySoftwareVersion = "qb2/ene/2.7.14"; ...