Home > Back-end >  How to use JSON_INSERT with the key that is in string?
How to use JSON_INSERT with the key that is in string?

Time:11-22

I'm not finding a way to use JSON_INSERT in a json whose key is a string:

{
 "computer": {
    "display": blue
  },
 "computer home":{}
}

This way it works:

JSON_INSERT(type, '$.computer.color', 'red');`

But not like this:

JSON_INSERT(type, '$.computer home.color', 'red');`

My wish:

{
 "computer" :{
    "display": "blue",
    "color": "red"

  },
 "computer home":{
   "color": "red"
 }
}

Apparently it's not working because the json key "computer home" has space, how can I insert it even with spaces?

CodePudding user response:

Here's a demo:

mysql> set @j = '{
 "computer": {
    "display": "blue"
  },
 "computer home":{}
}';

(note I had to put "blue" in double-quotes too; all strings must be delimited that way in JSON)

You can use JSON keys that contain spaces (or punctuation too) by delimiting them with double-quotes:

mysql> select json_insert(@j, '$."computer home".color', 'red') as result;
 ---------------------------------------------------------------------- 
| result                                                               |
 ---------------------------------------------------------------------- 
| {"computer": {"display": "blue"}, "computer home": {"color": "red"}} |
 ---------------------------------------------------------------------- 
  • Related