MySql操作Json字段


MySql json字段操作函數

分類 函數 描述
創建json json_array 創建json數組
  json_object 創建json對象
  json_quote 將json轉成json字符串類型
查詢json json_contains 判斷是否包含某個json值
  json_contains_path 判斷某個路徑下是否包json值
  json_extract 提取json值
  column->path json_extract的簡潔寫法,MySQL 5.7.9開始支持
  column->>path json_unquote(column -> path)的簡潔寫法
  json_keys 提取json中的鍵值為json數組
  json_search 按給定字符串關鍵字搜索json,返回匹配的路徑
修改json json_append 廢棄,MySQL 5.7.9開始改名為json_array_append
  json_array_append 末尾添加數組元素,如果原有值是數值或json對象,則轉成數組后,再添加元素
  json_array_insert 插入數組元素
  json_insert 插入值(插入新值,但不替換已經存在的舊值)
  json_merge 合並json數組或對象
  json_remove 刪除json數據
  json_replace 替換值(只替換已經存在的舊值)
  json_set 設置值(替換舊值,並插入不存在的新值)
  json_unquote 去除json字符串的引號,將值轉成string類型
返回json屬性 json_depth 返回json文檔的最大深度
  json_length 返回json文檔的長度
  json_type 返回json值得類型
  json_valid 判斷是否為合法json文檔

一、查詢json字段中某一個對象

 

SELECT id,jsontest,jsontest->'$.row' as row1,jsontest->'$.celldata' as celldata FROM `test`

 

 字符串返回的不同

SELECT id,jsontest,jsontest->'$.name' as name1, jsontest->>'$.name' as name2 FROM `test` where id=1

查詢時,不返回指定字段

 

SELECT id,json_remove(jsontest,"$.cell") from test where id=2;

二、更新json

update test set jsontest=json_set(jsontest,"$.x","vv")  where id=2;

update test set jsontest=json_set(jsontest,"$.x.z","bb")  where id=2;

替換整個對象

update test set jsontest=json_set(jsontest,"$.x",JSON_OBJECT("a","a1","b","b1"))  where id=2;

更新多個key

update test set jsontest=json_set(jsontest,"$.k2","1"), jsontest=json_set(jsontest,"$.k","2")  where id=2;

替換數組

update test set jsontest=json_set(jsontest,"$.x",JSON_Array("a1","a2","a3"))  where id=2;

插入數據組(對象為json字符串)

update test set jsontest=json_array_append(jsontest,"$.cell",CAST('{"r": 1, "v": "v1"}' as JSON))  where id=2;

 

三、刪除json

update test set jsontest=json_remove(jsontest,"$.x.a")  where id=2;

update test set jsontest=json_remove(jsontest,"$.x")  where id=2;

四、數組處理

示例:{"k": "vv", "cell": [{"r": 1, "v": "v1"}]}

update test set jsontest=json_array_append(jsontest,"$.cell",json_object("r",1, "v", "v1"))  where id=2;

插入到數組0

update test set jsontest=json_array_insert(jsontest,"$.cell[0]",json_object("r",2, "v", "v2"))  where id=2;

去除位置為1

update test set jsontest=json_remove(jsontest,"$.cell[1]")  where id=2;

更新集合位置x的對象中key的值 

update test set jsontest=json_set(jsontest,"$.cell2[1].r",CAST('{"ct":"test","v":1,"m":"1222"}' as JSON))  where id=2;

 

 

 

 

四、CAST使用

更新中

update test t set t.jsontest=json_set(t.jsontest,"$.x",CAST('{"a":"b"}' as JSON))  where id=2;

 

 

查詢中

SELECT t.jsontest->>'$.cell', CAST(t.jsontest->>'$.cell' AS JSON) from test t where t.id=2;

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM