0

I am using JSON_ARRAY_APPEND to update an array object in an existing entry in the table.

I am doing it via code and query looks as below:

UPDATE table t1
        SET t1.value = JSON_ARRAY_APPEND('[]', '$', JSON_OBJECT('desc', '${desc}', 
        'hosts', '[${hosts}]'))
        WHERE  t1.key = '${key1}
    

My resulting value looks as below:

[{"desc": "this is desc", "hosts": "[host1,host2, host3]"}] 

Desired Output for value is:

[{"desc": "this is desc", "hosts": ["host1","host2","host3"]"}] 
meallhour
  • 13,921
  • 21
  • 60
  • 117

2 Answers2

0

``

SELECT CONCAT('"', REPLACE('${hosts}', ',', '","'), '"');
UPDATE table t1
SET t1.value = JSON_ARRAY_APPEND('[]', '$', JSON_OBJECT('desc', '${desc}', 'hosts', '[${hosts}]'))
WHERE  t1.key = '${key1};


SET @host =  'host1,host2, host3';
UPDATE table t1
SET t1.value = JSON_ARRAY(
JSON_OBJECT(
'desc', 'this is desc', 
'hosts',
JSON_ARRAY(                           
SUBSTRING_INDEX(@host, ',', 1),
SUBSTRING_INDEX(SUBSTRING_INDEX(@host, ',', 2), ',', -1) ,
SUBSTRING_INDEX(SUBSTRING_INDEX(@host, ',', 3), ',', -1)))) ;

''

0

You don't need to use JSON_ARRAY_APPEND() since you are creating a new array.

Use JSON_ARRAY(). This ensures the array will be formatted as valid JSON. You should try to avoid writing code that forms JSON by concatenating commas and brackets and quotes, because it's difficult to ensure this will always produce valid JSON format. It's fragile code.

Also, use query parameters instead of trying to interpolate code variables into your SQL statement.

UPDATE table t1
SET t1.value = JSON_ARRAY( 
  JSON_OBJECT(
    'desc', ?, 
    'hosts', JSON_ARRAY(?, ?, ?, ?))
WHERE t1.key = ?

You'll need one ? parameter marker for each host you want in your hosts array.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828