"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve a Specific Object from a JSON Column in MySQL Based on Key-Value Pair?

How to Retrieve a Specific Object from a JSON Column in MySQL Based on Key-Value Pair?

Published on 2024-11-08
Browse:341

How to Retrieve a Specific Object from a JSON Column in MySQL Based on Key-Value Pair?

MySQL JSON: Searching Objects Based on Key Values

MySQL tables often utilize JSON columns to store complex data structures. When working with JSON, a common task is to retrieve a specific object based on a key-value pair. However, finding the object directly may not always be straightforward.

JSON Schema Example:

Consider the following schema:

CREATE TABLE `fields` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `label` varchar(64) COLLATE utf8mb4_unicode_ci NOT NULL,
  `options` json DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

With sample data:

INSERT INTO `fields` (label, options) VALUES
(
  'My Field', 
  '[{"text": "Grass", "value": "1"}, {"text": "Synthetic (New Type - Soft)", "value": "2"}, {"text": "Synthetic  (Old Type - Hard)", "value": "3"}, {"text": "Gravel", "value": "5"}, {"text": "Clay", "value": "6"}, {"text": "Sand", "value": "7"}, {"text": "Grass/Synthetic Mix", "value": "8"}]'
);

Problem:

Suppose we want to retrieve the string "Grass" from the options JSON array, knowing that its corresponding "value" is "1." Using JSON_EXTRACT() alone requires the index of the array, which may not be readily available.

Solution 1: Using JSON_SEARCH() and Horrible String Manipulation

This approach combines JSON_SEARCH() to partially find the index and then removes unwanted parts from the string:

SELECT
JSON_EXTRACT(`options`,CONCAT('$[',REPLACE(REPLACE(JSON_SEARCH(`options`, 'one', '1'), '"$[', ''), '].value"', ''), '].text'))
from `fields`;

Solution 2: Using JSON_TABLE()

MySQL 8.0 introduces JSON_TABLE() to simplify this task:

select field_options.* from fields cross join 
json_table(fields.options, 
'$[*]' columns(
  text text path '$.text',
  value text path '$.value'
 )
) as field_options 
where field_options.value = 1;

Alternative Approach: Relational Data Model

For simpler data structures like this example, consider storing the data in a relational table with columns for key and value pairs, allowing for direct search:

SELECT * FROM field_options WHERE value = '1';
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3