Ask Your Question
4

How can you remove items from a JSON array in MySQL that do not contain specific string values?

asked 2023-04-29 00:34:12 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-04-29 00:48:02 +0000

woof gravatar image

You can use the JSON_REMOVE function in MySQL to remove items from a JSON array that do not contain specific string values. Here is an example:

Assuming you have the following JSON array stored in a MySQL table:

[
   {"name": "Alice", "age": 25},
   {"name": "Bob", "age": 30},
   {"name": "Charlie", "age": 20},
   {"name": "David", "age": 35}
]

If you want to remove all items from the array that do not have the name "Bob", you can use the following SQL query:

UPDATE my_table SET my_column = JSON_REMOVE(my_column, REPLACE(JSON_SEARCH(my_column, 'one', 'Bob', NULL, '$[*]."name"'), '.name', ''))
WHERE JSON_CONTAINS(my_column, '"Bob"', '$[*]."name"') = 0;

This query uses the JSONSEARCH function to find the index of the item in the array that has the name "Bob", and then uses the JSONREMOVE function to remove all other items from the array. The WHERE clause filters out rows that do not contain the name "Bob" in any of the items in the array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-04-29 00:34:12 +0000

Seen: 9 times

Last updated: Apr 29 '23