I have a column in table which is stored in format:
{"field1":"val1","field2":"val4"}
{"field1":"val2","field2":"val5"}
{"field1":"val3","field2":"val6"}
I need to remove all field1 with values(e.g "field1":"val1","field1":"val2","field1":"val3" ) and result should be
{"field2":"val4"}
{"field2":"val5"}
{"field2":"val6"}
I am trying to acheive this via replace but stuck as in '"field1":"val1"' string val1 could be any value like null, some integer.
UPDATE emp SET col = REPLACE(col, '"field1":"val1"', '')
I am stuck due to this dynamic value of val1.
You need to double the backslash to escape it in JSON, and then double each of those to escape in the SQL string. If you print the JSON value it will show up as two backslashes, but that's because it shows the value in JSON format, which means that the backslash has to be escaped.
We can use the JSON_EXTRACT function to extract data from a JSON field. The basic syntax is: JSON_EXTRACT(json_doc, path) For a JSON array, the path is specified with $[index] , where the index starts from 0: mysql> SELECT JSON_EXTRACT('[10, 20, 30, 40]', '$[0]'); +------------------------------------------+
MySQL supports a native JSON data type defined by RFC 7159 that enables efficient access to data in JSON (JavaScript Object Notation) documents. The JSON data type provides these advantages over storing JSON-format strings in a string column: Automatic validation of JSON documents stored in JSON columns.
I would prefer to use the JSON_REMOVE function (MySQL) :
UPDATE emp
SET emp.col = JSON_REMOVE(emp.col, '$.field1');
You can also add a WHERE clause :
WHERE emp.col LIKE '%val6%';
References: MySQL JSON_REMOVE and MySQL JSON path
A blog post with examples: MySQL for your JSON
And a note about json path in MySQL:
Propery names in path must be double quoted if the property identifier contains interpunction (spaces, special characters, meta characters) bugs.mysql.com
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With