Get Started with JSON_OBJECT in MySQL

Get Started with JSON_OBJECT in MySQL

JSON_OBJECT

It is a list of key-value pairs and returns a JSON object.

Create a table with a column of data type JSON

CREATE TABLE Customer (
  id int unsigned PRIMARY KEY NOT NULL AUTO_INCREMENT,
  name varchar(100) NOT NULL,
  email varchar(100) NOT NULL,
  address JSON NOT NULL
);

To create a column with JSON data type assign it as JSON.

Insert values into table

INSERT INTO Customer (name, email, address) VALUES ('Cherish', 'cherish@gmail.com', '{"name": "customerLocation1", "address1": "320 Sector-12F", "address2": "Panaji, Goa", "province": "Goa", "country": "India" }');
INSERT INTO Customer (name, email, address) VALUES ('Clark', 'clark@gmail.com', '{"name": "customerLocation2", "address1": "500 Sector-10F", "address2": "Vaishali, Ghaziabad", "province": "Ghaziabad", "country": "India" }');
INSERT INTO Customer (name, email, address) VALUES ('Peter', 'peter@gmail.com', '{"name": "customerLocation1", "address1": "320 Sector-12F", "address2": "California, USA", "province": "California", "country": "USA" }');

Note: All values should be single-quoted and key-value pairs should be double-quoted.

Select operations on table

Select all data from the table

SELECT * FROM Customer;

Screenshot from 2022-08-15 17-33-34.png

Select custom JSON objects from table

SELECT JSON_OBJECT(
  'id', -- key
  cs.id, -- value
  'name',  
  cs.name, 
  'email', -- key
  cs.email, -- value
  'address', 
  cs.address 
) FROM Customer cs
WHERE id = 3;

Screenshot from 2022-08-15 17-31-23.png

Select JSON_TYPE

SELECT JSON_TYPE(address) FROM Customer;

Screenshot from 2022-08-15 17-36-06.png

Select specific key-value from JSON Object

This can be done in two ways:

  • inline path operator ->>
  • column-path operator ->
SELECT address->>"$.address1", address->"$.address1" FROM Customer;

Screenshot from 2022-08-15 17-42-25.png

Note: Inline-path operator leave surrounding quote marks but the Column-path operator includes them.

You've done it! Good Job!

Now you have complete knowledge of JSON_OBJECT. Try to do hands-on practice with it to gain full confidence.

Did you find this article valuable?

Support WeMakeDevs by becoming a sponsor. Any amount is appreciated!