Extract python list values in MYSQL
P粉153503989
P粉153503989 2023-09-04 19:35:45
0
2
437

I have a column in a MySQL database that contains a python list of values in json format, like this:

Column
[{"name":"me","color":"red"} , {"name":"you","color":"blue"}]

I cannot use the json_extract() function because its format is not exactly the same as json

I want to extract each json formatted in a new column like this:

First column Second column
{"Name": "I", "Color": "Red"} {"name":"you","color":"blue"}

P粉153503989
P粉153503989

reply all (2)
P粉311617763

The following query combined with the string manipulation functionsSUBSTRING_INDEX,REPLACE, andCONCATwill 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 aworking demonstration of using DBFIDDLE

This gives me the expected output:

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

Please replacemytablewith your_actual_table_name andcolumnwith 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!