SELECT JSON_VALUE(
'{ "name" : "Wag", "type" : "Dog", "weight" : 25 }',
'$.weight'
RETURNING DECIMAL(6,4)
Result:
25.0000
The ->
Operator
Another way to do it is to replace JSON_EXTRACT()
(or JSON_VALUE()
) with the ->
operator. The ->
operator is an alias for the JSON_EXTRACT()
function, and so we can use it to do anything we’d do with that function.
The ->
operator accepts a column identifier on the left and a JSON path on the right.
Suppose we have the following table called Pets
:
SELECT *
FROM Pets;
Result:
+-------+-----------------------------------------------+
| PetId | PetName |
+-------+-----------------------------------------------+
| 1 | {"name": "Wag", "type": "Dog", "weight": 20} |
| 2 | {"name": "Bark", "type": "Dog", "weight": 10} |
| 3 | {"name": "Meow", "type": "Cat", "weight": 7} |
+-------+-----------------------------------------------+
We can see that the PetName
column contains JSON.
We can use the ->
operator to extract data from fields within the JSON:
SELECT
PetId,
PetName -> '$.name',
PetName -> '$.type',
PetName -> '$.weight'
FROM Pets;
Result:
+-------+---------------------+---------------------+-----------------------+
| PetId | PetName -> '$.name' | PetName -> '$.type' | PetName -> '$.weight' |
+-------+---------------------+---------------------+-----------------------+
| 1 | "Wag" | "Dog" | 20 |
| 2 | "Bark" | "Dog" | 10 |
| 3 | "Meow" | "Cat" | 7 |
+-------+---------------------+---------------------+-----------------------+
The ->>
Operator
If we don’t want the string values to be enclosed in double quotes, we can use the ->>
operator.
The ->>
operator does basically the same thing as the ->
operator, except that it also unquotes the value:
SELECT
PetId,
PetName ->> '$.name',
PetName ->> '$.type',
PetName ->> '$.weight'
FROM Pets;
Result:
+-------+----------------------+----------------------+------------------------+
| PetId | PetName ->> '$.name' | PetName ->> '$.type' | PetName ->> '$.weight' |
+-------+----------------------+----------------------+------------------------+
| 1 | Wag | Dog | 20 |
| 2 | Bark | Dog | 10 |
| 3 | Meow | Cat | 7 |
+-------+----------------------+----------------------+------------------------+
JSON_UNQUOTE()
with the ->
Operator
If we can’t use the ->>
operator for whatever reason, we can use JSON_UNQUOTE()
to unquote the value returned by the ->
operator:
SELECT
PetId,
JSON_UNQUOTE(PetName -> '$.name')
FROM Pets;
Result:
+-------+-----------------------------------+
| PetId | JSON_UNQUOTE(PetName -> '$.name') |
+-------+-----------------------------------+
| 1 | Wag |
| 2 | Bark |
| 3 | Meow |
+-------+-----------------------------------+