How to get the JSON field types in MySQL
- 2 minutes read - 279 wordsTo get the type of a JSON item in MySQL you need to use the JSON_TYPE function.
NOTE: more info is available in the MySQL JSON functions documentation page
The dataset
The dataset is the following:
{
"id": 778,
"shop": "Luigis Pizza",
"name": "Edward Olson",
"phoneNumbers":
["(935)503-3765x4154","(935)12345"],
"address": "Unit 9398 Box 2056 DPO AP 24022",
"image": null,
"pizzas": [
{
"pizzaName": "Salami",
"additionalToppings": ["🥓", "🌶️"]
},
{
"pizzaName": "Margherita",
"additionalToppings": ["🍌", "🌶️", "🍍"]
}
]
}
Check out the description of the fields
The following examples use a pizza order dataset with an order having:id: 778shop: “Luigis Pizza”name: “Edward Olson”phoneNumbers:["(935)503-3765x4154","(935)12345"]address: “Unit 9398 Box 2056 DPO AP 24022”image: null- and two pizzas contained in the
pizzasitem:
[
{
"pizzaName": "Salami",
"additionalToppings": ["🥓", "🌶️"]
},
{
"pizzaName": "Margherita",
"additionalToppings": ["🍌", "🌶️", "🍍"]
}
]
If you want to reproduce the examples, check how to recreate the dataset
It can be recreated with the following script:
create table test(id serial primary key, json_data json);
insert into test(json_data) values (
'{
"id": 778,
"shop": "Luigis Pizza",
"name": "Edward Olson",
"phoneNumbers":
["(935)503-3765x4154","(935)12345"],
"address": "Unit 9398 Box 2056 DPO AP 24022",
"image": null,
"pizzas": [
{
"pizzaName": "Salami",
"additionalToppings": ["🥓", "🌶️"]
},
{
"pizzaName": "Margherita",
"additionalToppings": ["🍌", "🌶️", "🍍"]
}
]
}');
Extract a JSON field type using the JSON_TYPE function
You can get the type of JSON data with the JSON_TYPE function
select
JSON_TYPE(json_data -> '$.pizzas') pizzas
from test;
In the above query
json_data -> '$.pizzas'extracts thepizzasfield- the surrounding
JSON_TYPEretrieves the type
Result
+--------+
| pizzas |
+--------+
| ARRAY |
+--------+
Review all the JSON MySQL use-cases listed in the main page