How to create a JSON document from fields in MySQL
- 2 minutes read - 262 wordsYou can create a JSON document from fields in Mysql® with the JSON_OBJECT 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: 778
- shop: “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": ["🍌", "🌶️", "🍍"]
        }
    ]
}');
Create a JSON object with JSON_OBJECT function
To create a JSON document, from a list of fields or strings you can use the JSON_OBJECT function.
select 
    JSON_OBJECT('mykey1','myvalue1','mykey2','myvalue2') json_data;
Result
+----------------------------------------------+
| json_data                                    |
+----------------------------------------------+
| {"mykey1": "myvalue1", "mykey2": "myvalue2"} |
+----------------------------------------------+
Review all the JSON MySQL use-cases listed in the main page