Extract python list values ​​in MYSQL
P粉153503989
P粉153503989 2023-09-04 19:35:45
0
2
449
<p>I have a column in a MySQL database that contains a <code>python list</code> of values ​​in <code>json</code> format, like this: </p> <table class="s-table"> <thead> <tr> <th>Column</th> </tr> </thead> <tbody> <tr> <td>[{"name":"me","color":"red"} , {"name":"you","color":"blue"}]</td> </tr> </tbody> </table> <p>I cannot use the <code>json_extract()</code> function because its format is not exactly the same as <code>json</code></p> <p>I want to extract each <code>json</code> formatted in a new column like this: </p> <table class="s-table"> <thead> <tr> <th>First column</th> <th>Second column</th> </tr> </thead> <tbody> <tr> <td>{"Name": "I", "Color": "Red"}</td> <td>{"name":"you","color":"blue"}</td> </tr> </tbody> </table></p>
P粉153503989
P粉153503989

reply all(2)
P粉311617763

The following query combined with the string manipulation functions SUBSTRING_INDEX, REPLACE, and CONCAT will yield the expected results.

SELECT 
  CONCAT('{', REPLACE(SUBSTRING_INDEX(SUBSTRING_INDEX(`column`, '}', 1), '{', -1), '\"', '"'), '}') AS First_column,
  CONCAT('{', REPLACE(SUBSTRING_INDEX(SUBSTRING_INDEX(`column`, '}', 2), '{', -1), '\"', '"'), '}') AS Second_column
FROM mytable;

Here is a working demonstration of using DBFIDDLE

This gives me the expected output:

first row The second column
{"Name": "I", "Color": "Red"} {"name":"you","color":"blue"}

Please replace mytable with your_actual_table_name and column with your actual column name. I surrounded the columns with backticks because column is a reserved keyword in sql.

P粉445714413

You should be able to use JSON_EXTRACT on the example columns included in the question:

SET @column = '[{"name":"me","color":"red"} , {"name":"you","color":"blue"}]';

SELECT
    JSON_EXTRACT(@column, '$[0]') AS First_column,
    JSON_EXTRACT(@column, '$[1]') AS Second_column;

Output:

first row The second column
{"Name": "I", "Color": "Red"} {"Name": "You", "Color": "Blue"}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!