2017-01-24 71 views
0

我有以下存儲在MySQL的JSON對象:的MySQL 5.7 JSON_EXTRACT使用

[ 
    { 
    "key": "user_agent", 
    "value": "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; rv:11.0) like Gecko" 
    }, 
    { 
    "key": "language", 
    "value": "fr-FR" 
    }, 
    { 
    "key": "color_depth", 
    "value": 24 
    }, 
    { 
    "key": "js_fonts", 
    "value": [ 
     "Arial", 
     "Arial Black" 
    ] 
    } 
] 

你能幫可以選擇從該JSON第二或第一個值。可選地,其中「key」例如是「user_agent」。我想這樣會更好,因爲價值訂單不能保證。 我只是不能真正弄明白,如何使用JSON路徑中描述: https://dev.mysql.com/doc/refman/5.7/en/json-path-syntax.html

爲了方便,這裏是SQL語句創建示例表:

CREATE TABLE `test` (
    `components` json NOT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

INSERT INTO `test` VALUES ('[{\"key\": \"user_agent\", \"value\": \"Mozilla/5.0 (Windows NT 6.1; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E; r1.0) like Gecko\"}, {\"key\": \"language\", \"value\": \"fr-FR\"}, {\"key\": \"color_depth\", \"value\": 24}, {\"key\": \"js_fonts\", \"value\": [\"Arial\", \"Arial Black\"]}]'); 

JSON_EXTRACT(組件, '$ [1]')提取第二個數組:

{"key": "language", "value": "fr-FR"} 

但它不完全是我想要的。

回答

0

好吧,這比我想象的要容易。至少要解壓:

SELECT JSON_EXTRACT(components, '$[0].value') FROM test; 

返回我想要的。或使用較短語法的未加引號結果:

SELECT components - >>'$ [0] .value'FROM test;