MariaDBでは、JSON_VALUE() JSONドキュメントからスカラー値を返す組み込み関数です。具体的には、指定されたパスで指定されたスカラーを返します。
構文
構文は次のようになります:
JSON_VALUE(json_doc, path)
json_docの場所 はJSONドキュメントであり、path ドキュメント内のパスです。
例
実例を示します。
SET @json_document = '
{
"name": "Wag",
"type": "Dog",
"weight": 20
}
';
SELECT JSON_VALUE(@json_document, '$.name'); 結果:
+--------------------------------------+ | JSON_VALUE(@json_document, '$.name') | +--------------------------------------+ | Wag | +--------------------------------------+
存在しないパス
JSONドキュメントに存在しないパスを渡すと、NULLになります 。
例:
SET @json_document = '
{
"name": "Wag",
"type": "Dog",
"weight": 20
}
';
SELECT JSON_VALUE(@json_document, '$.color'); 結果:
+---------------------------------------+ | JSON_VALUE(@json_document, '$.color') | +---------------------------------------+ | NULL | +---------------------------------------+
配列
配列からデータを返す例は次のとおりです。
SET @json_document = '
{
"_id" : 1,
"awards" : [ "Top Dog", "Best Dog", "Biggest Dog" ]
}
';
SELECT JSON_VALUE(@json_document, '$.awards[1]'); 結果:
+-------------------------------------------+ | JSON_VALUE(@json_document, '$.awards[1]') | +-------------------------------------------+ | Best Dog | +-------------------------------------------+
配列はゼロベースであるため、$.awards[1] awardsの2番目の要素を抽出します 配列。
ネストされたオブジェクト
別のオブジェクト内にネストされたオブジェクトから値を取得する例を次に示します。
SET @json_document = '
{
"_id" : 1,
"name" : "Wag",
"details" : {
"type" : "Dog",
"weight" : 20,
"awards" : {
"Florida Dog Awards" : "Top Dog",
"New York Marathon" : "Fastest Dog",
"Sumo 2020" : "Biggest Dog"
}
}
}
';
SELECT JSON_VALUE(
@json_document,
'$.details.awards.Florida Dog Awards'
) AS Result; 結果:
+---------+ | Result | +---------+ | Top Dog | +---------+
非スカラー値
非スカラー値(オブジェクトや配列など)を返そうとすると、NULLが返されます。 。
例:
SET @json_document = '
{
"_id" : 1,
"name" : "Wag",
"details" : {
"type" : "Dog",
"weight" : 20,
"awards" : {
"Florida Dog Awards" : "Top Dog",
"New York Marathon" : "Fastest Dog",
"Sumo 2020" : "Biggest Dog"
}
}
}
';
SELECT JSON_VALUE(
@json_document,
'$.details.awards'
) AS Result; 結果:
+--------+ | Result | +--------+ | NULL | +--------+
非スカラー値を返すには、JSON_QUERY()を使用します 関数またはJSON_EXTRACT() 機能。
ヌル引数
引数がNULLの場合 、結果はNULLです :
SELECT
JSON_VALUE(null, '$.type'),
JSON_VALUE('{"a":1}', null); 結果:
+----------------------------+-----------------------------+
| JSON_VALUE(null, '$.type') | JSON_VALUE('{"a":1}', null) |
+----------------------------+-----------------------------+
| NULL | NULL |
+----------------------------+-----------------------------+ パラメータカウントが正しくありません
引数を指定しないとエラーが発生します:
SELECT JSON_VALUE(); 結果:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_VALUE'
提供する引数が少なすぎても多すぎても同じです:
SELECT JSON_VALUE('{ "a": 1}'); 結果:
ERROR 1582 (42000): Incorrect parameter count in the call to native function 'JSON_VALUE'