首頁  >  問答  >  主體

在 MYSQL 中提取 python 列表值

<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粉153503989P粉153503989412 天前474

全部回覆(2)我來回復

  • P粉311617763

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

    以下查詢結合字串運算元 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 中的保留關鍵字。 ###

    回覆
    0
  • P粉445714413

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

    您應該能夠在問題中包含的範例列上使用 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;
    

    輸出:

    第一列 第二列
    {“名稱”:“我”,“顏色”:“紅色”} {“名稱”:“你”,“顏色”:“藍色”}

    回覆
    0
  • 取消回覆