Search and extract JSON data in MySQL

Currently, I am inputting JSON objects into a MySQL Database and then executing queries on them. Within the database is a table structured as follows:

subjects                                                |
---------------------------------------------------------
|{
|"subjects": [{
|  "subject":"English Language & Literature",
|  "ageRange":["12-18"],
|  "examlevel":["13+","gcse","as-level","a-level"],
|  "examboard":["aqa","edexcel","ocr","wjec"]
|},
|{
|  "subject":"Creative Writing",
|  "ageRange":["8-18"],                                     | Row 1
|  "examlevel":null,
|  "examboard":null
|},
|{
|  "subject":"Media Studies",
|  "ageRange":["14-18"],
|  "examlevel":["gcse","as-level","a-level"],
|  "examboard":["aqa","edexcel","ocr","wjec"]
|}]
|}
---------------------------------------------------------

In one of my MySQL queries, I executed

SELECT JSON_EXTRACT(subjects, '$."subjects"') FROM `table_name`

This returned

[{"subject": "English Language & Literature", "age...

To extract the subject name, I ran the following...

SELECT JSON_EXTRACT(subjects, '$."subjects[*]."subject"') FROM `table_name` 

The result was

["English Language & Literature", "Creative Writin...

I then attempted to run a search query against the extracted JSON data

SELECT JSON_EXTRACT(subjects, JSON_UNQUOTE(JSON_SEARCH(subjects, 'all', '{Search Query i.e "E"}', NULL, '$."subjects"[*]."subject"'))) FROM `table_name`

This ^^ resulted in NULL

My goal is to dive deeper into querying. I aim to extract the subject name from each JSON object for all subjects within this group. Essentially, the search should iterate through each subject field in every JSON Object for all rows to yield results matching the search query.

Despite consulting the MySQL Docs, the information provided has not been very helpful... Now that I have obtained the Extracted JSON data, how can I perform searches against them? Furthermore, how can I selectively retrieve only those matching the search query?

Answer №1

After analyzing the feedback provided, I have discovered effective solutions to the problem at hand.

The following query will retrieve the columns with an exact match to the specified string:

SELECT JSON_EXTRACT(subjects, JSON_UNQUOTE(JSON_SEARCH(subjects,'all','Creative Writing', NULL, '$."subjects"[*]."subject"'))) FROM `table_name`

--

SELECT JSON_EXTRACT(subjects, JSON_UNQUOTE(JSON_SEARCH(LOWER(subjects),'all',LOWER('%eng%'), NULL, '$."subjects"[*]."subject"'))) FROM `table_name`

This query will fetch the columns containing the characters 'eng' in a case-insensitive manner, ensuring all relevant rows are retrieved.

--

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

Issue with Angular 7 service worker caching audio files leads to range header problems in Safari browser

I am encountering an issue in my Angular application with the range request header for audio files when using Safari. When requesting audio from a server, the duration of the audio file is returned correctly. However, when requesting the audio from the ser ...

Is it possible to merge a dictionary with text file writing and then retrieve it as a dictionary once again?

I am making requests to a link and receiving JSON files as response. I am storing this data in a text file, but when I try to read it back, I want to interpret it as a dictionary. How can I achieve this? def url_sequence(limit=5): for i in range(limit ...

The issue I am facing is with the post_logout_redirect_uri not functioning properly when using localStorage in an OIDC Auth

authority: 'yyy', client_id: this.'yyy', redirect_uri: 'http://localhost:4200/login', response_type: 'token', scope: 'yyy', post_logout_redirect_uri: & ...

What steps should I take to fix the TypeScript Compiler issue "Global member 'NodeJS' has no exported namespace 'Global'?"

QUERY: What steps should I take to fix the Typescript Compiler (tsc) error stating "Namespace 'NodeJS' has no exported member 'Global'"? Upon executing tsc, this particular error unexpectedly appeared in a project that is considered "l ...

"Encountering a problem with the client-session middleware: the value of req.session_state is becoming undefined

I'm facing an issue with client-session middleware in Express. After setting the session_state, it doesn't seem to be accessible when redirecting to a new route. I followed a tutorial on YouTube (client-session part starts at around 36:00) and do ...

What are the steps for integrating mongoDB with an angular2 application?

I currently have my angular2 & mongoDB setup successfully. While I've managed to read JSON files using the HTTP service, my goal is to create a fully functional application with database connectivity as well. I'm seeking advice on how to con ...

Parsing large numbers in JSON data using the json_decode function

Facing an issue while decoding a json string The PHP version being used is 5.4.4-7 and the operating system is Debian amd64. Here is the JSON string: {"status":"success","account":{"buy_title":"KGP ID","birthday":0,"sex":0,"phone_number":"","avatar":"ht ...

Comparing a series of smaller strings to a larger string for testing purposes

My website has an array filled with bot names. Whenever a user or bot visits the site, I retrieve the user-agent and want to check if any of the values in my array are present in it. var bots = [ "twitterbot", "linkedinbot", "facebookexternalhit", ...

nodemailer failed to authenticate login: 535 Authentication Error

I'm encountering a 535 Authentication Failed error when trying to utilize the nodemailer npm package in my node application for sending emails through the contact page. My email and password are correct, so I'm unsure why this issue is arising. v ...

Is there an alternative method to retrieve the client's user agent if getStaticProps and getServerSideProps cannot be used together?

I am currently facing a challenge with the website I'm working on as it lacks a responsive design. This means that the view I display is dependent on the user agent of the client. In order to achieve this, I have been using getServerSideProps to deter ...

How to style a div for printing using CSS

Currently, I am working on a project that has already been completed but now requires some enhancements. To give you an overview, the project includes a search functionality that displays additional details upon clicking on the displayed name in the result ...

Adding ngChange programmatically in Angular without using attributes is a common challenge faced

I am attempting to replicate the functionality of the ng-change attribute within a directive without making changes to the HTML (thus excluding the use of the ng-change property). After examining the Angular source code for the ngChange directive, I have ...

Using Selenium Webdriver to initiate the play function of a video by clicking on the control

Is there a way to play the video on this page by clicking the play button? I noticed a 'playpause' control in the JavaScript, but I'm unsure how to activate it. <div id="videoModal" class="reveal-modal expand open" style="display: block ...

"Encountered a syntax error while attempting to reference an attribute on an empty object

> "[object Number]" === Object.prototype.toString.call(1) // #1 < true > "[object Number]" === {}.toString.call(1) // #2 < true > {}.toString.call(1) === "[object Number]" // #3 < SyntaxError: Unexpected token ...

Understanding Node.js document object

Hey, I'm currently trying to execute a JavaScript function on the server side using node.js, but I've encountered an issue. The function relies on accessing hidden values within the returned HTML using the document DOM, however, the document obje ...

Using `this` in a Jquery get() call to reference a callback function

Utilizing the this keyword in the callbacks of $.get() is my current challenge. The outline of my code looks like this: var myObject = { get: function() { $.get(server,data,function(data,status) { this.callback(); }); }, callback: func ...

Automatically selecting and fetching checkbox values using JavaScript

I was struggling with coding a function that involved generating checkboxes using JavaScript. My goal is to automatically select the elements "March" and "September" from the array target[] and display them as checked in the text area. So, "March" and "Se ...

It appears that utf8_unicode_ci is not actually encoding characters in UTF8

Recently, I encountered an unusual issue with my mySql database. Despite encoding my tables in "utf8_unicode_ci," when I perform a SELECT query, the data does not seem to be in UTF8 format as json_encode returns empty strings. To resolve this issue, I hav ...

I'm currently attempting to establish a connection between my server.js express API and MongoDB, but I keep encountering an unfamiliar error message that I'm having trouble decipher

Here is the server.js code: import express from 'express'; import bodyParser from 'body-parser'; import userRoutes from './routes/users.js'; import mongoose from 'mongoose'; co ...

JavaScript is incapable of locating image files

I am encountering Resource Not Found errors for the image files I am attempting to load into var manifest. Despite following the tutorial code closely, I can't seem to identify what is causing this issue... (function () { "use strict"; WinJS.Bin ...