Extract python list values in MYSQL
P粉153503989
2023-09-04 19:35:45
<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>
The following query combined with the string manipulation functions
SUBSTRING_INDEX
,REPLACE
, andCONCAT
will yield the expected results.Here is a working demonstration of using DBFIDDLE
This gives me the expected output:
Please replace
mytable
with your_actual_table_name andcolumn
with your actual column name. I surrounded the columns with backticks because column is a reserved keyword in sql.You should be able to use JSON_EXTRACT on the example columns included in the question:
Output: