在 MYSQL 中提取 python 列表值
P粉153503989
P粉153503989 2023-09-04 19:35:45
0
2
539
<p>我在 MySQL 資料庫中有一個列,其中包含 <code>json</code> 格式值的 <code>python 清單</code>,如下:</p> <table class="s-table"> <thead> <tr> <th>列</th> </tr> </thead> <tbody> <tr> <td>[{"name":"me","color":"red"} , {"name":"you","color":"blue"}]</td> </tr> </tbody> </table> <p>我無法使用 <code>json_extract()</code> 函數,因為它的格式與 <code>json</code> 不完全相同</p> <p>我想提取新欄位中已格式化的每個 <code>json</code> ,如下:</p> <table class="s-table"> <thead> <tr> <th>第一列</th> <th>第二列</th> </tr> </thead> <tbody> <tr> <td>{“名稱”:“我”,“顏色”:“紅色”}</td> <td>{"name":"you","color":"blue"}</td> </tr> </tbody> </table></p>
P粉153503989
P粉153503989

全部回覆(2)
P粉311617763

以下查詢結合字串運算元 SUBSTRING_INDEXREPLACECONCAT 將獲得預期結果。

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;

這裡是使用 DBFIDDLE 的工作演示

#這給了我預期的輸出:

第一列 第二列
{“名稱”:“我”,“顏色”:“紅色”} {"name":"you","color":"blue"}

# 請將 mytable 替換為 your_actual_table_name,並將 column

替換為您的實際欄位名稱。我用反引號包圍了列,因為列是 sql 中的保留關鍵字。 ###
P粉445714413

您應該能夠在問題中包含的範例列上使用 JSON_EXTRACT:

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;

輸出:

第一列 第二列
{“名稱”:“我”,“顏色”:“紅色”} {“名稱”:“你”,“顏色”:“藍色”}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板