Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append property to JSON object in MySQL

Tags:

json

mysql

I have a table in MySQL whose column user_json holds a JSON value like this..

{
  "user": {
    "firstName": "Joe",
    "lastName":"Rizzo"
  },
  "city":"Salisbury"
}

I want to add an email address property to the existing JSON so the result should look like..

{
  "user": {
    "firstName": "Joe",
    "lastName":"Rizzo",
    "emailAddress":"[email protected]"
  },
  "city":"Salisbury"
}

I thought I could use JSON_INSERT like so....

update my_table set user_json = 
JSON_INSERT(user_json, '$. user', JSON_OBJECT("emailAddress","[email protected]")) where id = 4783

But this didn't update the JSON. Is there any other way to accomplish this?

like image 269
AbuMariam Avatar asked Oct 19 '25 05:10

AbuMariam


1 Answers

Updated 2022-03-15

I believe JSON_INSERT() accepts a key-value pair (where the path is the key). So you don't need JSON_OBJECT(). Instead try:

 UPDATE YourTable  
 SET    user_json = JSON_INSERT(user_json
                           , '$.user.emailAddress'
                           , '[email protected]')
 WHERE  id = 4783

Results:

{
  "city": "Salisbury",
  "user": {
    "lastName": "Rizzo",
    "firstName": "Joe",
    "emailAddress": "[email protected]"
  }
}

db<>fiddle here

like image 181
SOS Avatar answered Oct 21 '25 19:10

SOS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!