1

I have a requirement that I need to write a mysql function which takes 'JSONText', 'color' as parameters and output based on the 'color'

[ 
  {
    "color":"red",
    "points":4
  },
  {
    "color": "Electric Blue",
    "points": 5
  }
 ]

So, my function would be

 DELIMITER $$
 CREATE FUNCTION GetColorPoints(JSONParam Text, color VARCHAR(10)) RETURNS INT
 BEGIN
        **???** //WHAT SHOULD GO HERE??
 END$$
 DELIMITER;

So, if I call the function with inputs, it should give me points.

 SELECT GetColorPoints('[ {"color":"red", "points":4}, {"color": "Electric Blue", "points": 5} ]', 'Electric Blue') AS 'ColorPoints';
GMB
  • 216,147
  • 25
  • 84
  • 135
Srinivas Lakshman
  • 469
  • 2
  • 4
  • 21

1 Answers1

2

If you are happy enough to use MySQL 8.0, you can do this with JSON_TABLE():

set @js = '[ { "color":"red", "points":4 }, { "color": "Electric Blue", "points": 5 } ]';
select points
from json_table(
    @js,
    '$[*]' columns(
        color varchar(50) path '$.color',
        points int path '$.points'
    )
) t
where color = 'red'
GMB
  • 216,147
  • 25
  • 84
  • 135