Home  >  Q&A  >  body text

Extract python list values ​​in MYSQL

<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粉153503989P粉153503989431 days ago490

reply all(2)I'll reply

  • P粉311617763

    P粉3116177632023-09-05 18:49:35

    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.

    reply
    0
  • P粉445714413

    P粉4457144132023-09-05 17:11:12

    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"}

    reply
    0
  • Cancelreply