首頁 > 軟體

關於mysql中的json解析函數JSON_EXTRACT

2022-07-05 14:06:05

mysql json解析函數JSON_EXTRACT

MYSQl自帶的解析函數JSON_EXTRACT,用JSON_EXTRACT函數解析出來的函數會包含雙引號

例子

t_table表裡面source欄位是以json格式寫的值為

{ "info" : { "color" : "白色", "inner_color" : "米色", "number" : "12345678", "registration_date" : "2012-11" },
"accessory" : [ "1", "4", "5", "6", "7", "8", "9", "10" ],
"remark" : "測試"}

查詢color不去掉雙引號,inner_color去掉雙引號,remark去掉雙引

select 
source->'$.info.color'  as color,
replace(source->'$.info.inner_color','"','')   as inner_color,
replace(source->'$.remark','"','')   as remark
 from t_table

查詢結果

colorinner_colorremark
“白色”米色測試

mysql5.7 json格式與json_extract方法

資料初始化

json_test表資料,id和jsonstr欄位(型別json)

{
    "no": "7",
    "title": "運動方式",
    "content": [{
        "text": "您平時經常進行的運動及時間",
        "item1": [{
            "text": "慢跑 / 快走 / 走跑結合",
            "type": "select",
            "value": "selected"
        }, {
            "text": "上下樓梯 / 爬山",
            "type": "multselect",
            "value": "selected"
        }],
        "item2": [{
            "text": "慢跑222走跑結合",
            "type": "text",
            "value": "慢跑2"
        }, {
            "text": "上下樓梯 / 爬山2",
            "type": "number",
            "value": "33"
        }]
    }]
}

select語句

SELECT
    id,
    json_extract( t.jsonstr, '$.*' ),
    json_extract( t.jsonstr, '$.title' ) AS "title",
    json_extract( t.jsonstr, '$.content' ) AS "content" ,
    json_extract( t.jsonstr, '$**.text' ) AS "text" ,
    json_extract( t.jsonstr, '$.content[*].item1[*]' ) AS "item1" 
FROM
    json_test t;

返回結果解析

//json_extract( t.jsonstr, '$.*' )返回:
["7", "運動方式", [{"text": "您平時經常進行的運動及時間", "item1": [{"text": "慢跑 / 快走 / 走跑結合", "type": "select", "value": "selected"}, {"text": "上下樓梯 / 爬山", "type": "multselect", "value": "selected"}], "item2": [{"text": "慢跑222走跑結合", "type": "text", "value": "慢跑2"}, {"text": "上下樓梯 / 爬山2", "type": "number", "value": "33"}]}]]
//json_extract( t.jsonstr, '$.title' ) AS "title"返回:
"運動方式"
//json_extract( t.jsonstr, '$.content' ) AS "content" 返回:
[{"text": "您平時經常進行的運動及時間", "item1": [{"text": "慢跑 / 快走 / 走跑結合", "type": "select", "value": "selected"}, {"text": "上下樓梯 / 爬山", "type": "multselect", "value": "selected"}], "item2": [{"text": "慢跑222走跑結合", "type": "text", "value": "慢跑2"}, {"text": "上下樓梯 / 爬山2", "type": "number", "value": "33"}]}]
//json_extract( t.jsonstr, '$**.text' ) AS "text" 返回:
["您平時經常進行的運動及時間", "慢跑 / 快走 / 走跑結合", "上下樓梯 / 爬山", "慢跑222走跑結合", "上下樓梯 / 爬山2"]
//json_extract( t.jsonstr, '$.content[*].item1[*]' ) AS "item1" 返回:
[{"text": "慢跑 / 快走 / 走跑結合", "type": "select", "value": "selected"}, {"text": "上下樓梯 / 爬山", "type": "multselect", "value": "selected"}]

用法解析

‘$.*’返回全部json
‘$.title’返回key=”title”的資料
‘$**.text’返回所有最底層key=”text”的資料
‘$.content[*].item1[*]’返回key=content的list的key=item1的list的所有內容

官方檔案:https://dev.mysql.com/doc/refman/5.7/en/json.html

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com