0

I am trying to delete objects from my JSON array in MySQL.

I have a table called cart with two fields quote_id type int and items type json with the following row stored inside MySQL

quote_id: 0

items:

[ { "a":42, "b":"test4" }, { "a":32, "b":"test3" } ]

I am trying to create a query which would delete json objects from the json array. For example every { "a":32, "b":"test3" }

I have tried many queries. First I ended up with this:

UPDATE cart
SET items = IFNULL(JSON_REMOVE(items, JSON_UNQUOTE(JSON_SEARCH(items, 'one', 'test3'))), items)
WHERE quote_id = 13392;

However it just deletes "b":"test3" from the second object and left the "a":32 in it and I need a query that would find the whole object and would delete it.

This is my second query:

UPDATE cart
SET items = IFNULL(JSON_REMOVE(items, JSON_SEARCH(items, 'one', CAST('{"a": 32, "b": "test3"}' AS JSON))), items)
WHERE quote_id = 13392;

However I don't think the search on it works. I tried it without using the CAST()AS JSON, however it still did not work.

As I said I am pretty sure the problem is with the JSON_SEARCH, but maybe someone has the solution?

Thank you!

2
  • What is your datatype of that field? Commented May 8, 2019 at 6:36
  • Which one, info? It's JSON. Commented May 8, 2019 at 7:05

1 Answer 1

1

The JSON_SEARCH returns the path of the property, not the path to the object itself.

So you can use the following solution to get the object path with SUBSTR:

SELECT JSON_REMOVE(items, 
    SUBSTR(JSON_UNQUOTE(JSON_SEARCH(items, 'one', 'test3')), 1, LOCATE('.', JSON_UNQUOTE(JSON_SEARCH(items, 'one', 'test3')))-1)
) FROM cart

You can also use REGEXP_SUBSTR to get the object path:

SELECT JSON_REMOVE(items, REGEXP_SUBSTR(JSON_UNQUOTE(JSON_SEARCH(items, 'one', 'test3')), '^\\$\\[[0-9]+\\]'))
FROM cart

demo on dbfiddle.uk

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.