SlideShare a Scribd company logo
JSON
Validation
Dave Stokes
MySQL Community Manager
MySQL Community Team
Dave Stokes
MySQL Community Team
Oracle Corporation
@Stoker
https://elephantdolphin.blogspot.com/
David.Stokes@Oracle.com
Slides are available at Slideshare.net/davestokes
2
3
JSON
JSON (JavaScript Object Notation is an open standard file format,
and data interchange format, that uses human-readable text to store
and transmit data objects consisting of attribute–value pairs and array
data types (or any other serializable value). It is a very common data
format, with a diverse range of applications, such as serving as a
replacement for XML in AJAX systems.
JSON is a language-independent data format. It was derived from
JavaScript, but many modern programming languages include code
to generate and parse JSON-format data
-- https://en.wikipedia.org/wiki/JSON
{ "GNP": 8510700,
"_id": "USA",
"Name": "United States",
"IndepYear": 1776,
"geography": {
"Region": "North America",
"Continent": "North America",
"SurfaceArea": 9363520
},
"government": {
"HeadOfState": "George W. Bush",
"GovernmentForm": "Federal Republic"
},
"demographics": {
"Population": 278357000,
"LifeExpectancy": 77.0999984741211
}
}
4
What does JSON look like?
{ "GNP": 8510700,
"_id": "USA",
"Name": "United States",
"IndepYear": 1776,
"geography": {
"Region": "North America",
"Continent": "North America",
"SurfaceArea": 9363520
},
"government": {
"HeadOfState": "George W. Bush",
"GovernmentForm": "Federal Republic"
},
"demographics": {
"Population": 278357000,
"LifeExpectancy": 77.0999984741211
}
}
5
What does JSON look like?
KEY : VALUE
{ "GNP": 8510700,
"_id": "USA",
"Name": "United States",
"IndepYear": 1776,
"geography": {
"Region": "North America",
"Continent": "North America",
"SurfaceArea": 9363520
},
"government": {
"HeadOfState": "George W. Bush",
"GovernmentForm": "Federal Republic"
},
"demographics": {
"Population": 278357000,
"LifeExpectancy": 77.0999984741211
}
}
6
What does JSON look like?
Document enclosed in brackets {}
OBJECTS are enclosed in {}
JSON: OBJECTS versus ARRAYS
7
Arrays are enclosed in []
8
Pretty
much
Free Form
Strict data types
INT, CHAR, DECIMAL, etc.
Optional
Required columns
Default Values
Constraint Checks, including range
Relational Databases
9
All these features can enforce rigor on you data to
ensure that it is properly formatted BEFORE it
gets saved in the database.
BTW - Much less expensive to keep bad data out
than having to correct it later!
10
Strict
versus
Free Form
JSON’s Freeform Can hurt
How would you save email address?
email: user@foo.com
eMail: user@foo.com
e-mail: user@foo.com
electronicMail: user@foo.com
EMail: user@foo.com
eMaIl: user@foo.com
Each of the keys here are unique and valid
Searching for email addresses would require being able to look for all the forms!
11
12
Some Examples of keeping data clean
create table percona (id int, name char(25));
insert into percona values ('test');
ERROR: 1136: Column count doesn't match value count at row 1
CREATE table pz (id int, name char(25) not null);
insert into pz (id) values (1);
ERROR: 1364: Field 'name' doesn't have a default value
CREATE TABLE check_plz ( c1 int constraint c1_not_42_error check (c1 <> 42) default 42,
c2 int default 42);
Query OK, 0 rows affected (0.2902 sec)
insert into check_plz (c2) values(NULL);
ERROR: 3819: Check constraint 'c1_not_42_error' is violated.
13
But what if
there was a way
to check JSON data?
14
15
16
The Functions
JSON_SCHEMA_VALID(schema,document)
Validates a JSON document against a JSON schema.
Both schema and document are required.
The schema must be a valid JSON object; the document must be a valid JSON document.
Provided that these conditions are met:
If the document validates against the schema, the function returns true (1);
otherwise, it returns false (0).
17
The Functions
JSON_SCHEMA_VALIDATION_REPORT(schema,document)
Validates a JSON document against a JSON schema.The schema must be a valid JSON object, and the
document must be a valid JSON document. Provided that these conditions are met, the function returns a
report, as a JSON document, on the outcome of the validation. If the JSON document is considered valid
according to the JSON Schema, the function returns a JSON object with one property valid having the
value "true".
If the JSON document fails validation, the function returns a JSON object which includes the properties
listed here:
○ valid: Always "false" for a failed schema validation
○ reason: A human-readable string containing the reason for the failure
○ schema-location: A JSON pointer URI fragment identifier indicating where in the JSON
schema the validation failed (see Note following this list)
○ document-location: A JSON pointer URI fragment identifier indicating where in the JSON
document the validation failed (see Note following this list)
○ schema-failed-keyword: A string containing the name of the keyword or property in the JSON
schema that was violated
18
Simple Example 1 -- the exemplar, the new document, and the test
set @s='{"type": "object",
"properties": {
"myage": {
"type" : "number",
"minimum": 28,
"maximum": 99
}
}
}';
set @d='{ "myage": 33}'
select JSON_SCHEMA_VALID(@s,@d);
+--------------------------+
| JSON_SCHEMA_VALID(@s,@d) |
+--------------------------+
| 1 |
+--------------------------+
1 row in set (0.00 sec)
19
Simple Example 2 -- the exemplar, the new document, and the test
set @s='{"type": "object",
"properties": {
"myage": {
"type" : "number",
"minimum": 28,
"maximum": 99
}
}
}';
set @d='{ "myage": “foo”}'
select JSON_SCHEMA_VALID(@s,@d);
+--------------------------+
| JSON_SCHEMA_VALID(@s,@d) |
+--------------------------+
| 0 |
+--------------------------+
1 row in set (0.00 sec)
20
Simple Example 3 -- the exemplar, the new document, and the test
set @s='{"type": "object",
"properties": {
"myage": {
"type" : "number",
"minimum": 28,
"maximum": 99
}
}
}';
set @d='{ "myage": 16}'
select JSON_SCHEMA_VALID(@s,@d);
+--------------------------+
| JSON_SCHEMA_VALID(@s,@d) |
+--------------------------+
| 0 |
+--------------------------+
1 row in set (0.00 sec)
select JSON_PRETTY(JSON_SCHEMA_VALIDATION_REPORT(@s,@d))G
*************************** 1. row ***************************
JSON_PRETTY(JSON_SCHEMA_VALIDATION_REPORT(@s,@d)): {
"valid": false,
"reason": "The JSON document location '#/myage' failed requirement 'minimum'
at JSON Schema location '#/properties/myage'",
"schema-location": "#/properties/myage",
"document-location": "#/myage",
"schema-failed-keyword": "minimum"
}
JSON_SCHEMA_VALIDATION_REPORT()
21
CREATE TABLE `testx` (
`col` JSON,
CONSTRAINT `myage_inRange`
CHECK (JSON_SCHEMA_VALID('{"type": "object",
"properties": {
"myage": {
"type" : "number",
"minimum": 28,
"maximum": 99
}
},"required": ["myage"]
}', `col`) = 1)
);
REQUIRE Fields
22
CREATE TABLE `testx` (
`col` JSON,
CONSTRAINT `myage_inRange`
CHECK (JSON_SCHEMA_VALID('{"type": "object",
"properties": {
"myage": {
"type" : "number",
"minimum": 28,
"maximum": 99
}
},"required": ["myage"]
}', `col`) = 1)
);
REQUIRE Fields
23
insert into testx values('{"myage":27}');
ERROR 3819 (HY000):
Check constraint 'myage_inRange' is
violated.
insert into testx values('{"myage":97}');
Query OK, 1 row affected (0.02 sec)
24
❏ MySQL Manual -- https://dev.mysql.com/doc/refman/8.0/en/json-validation-functions.html
❏ Understanding JSON Schema -- http://json-schema.org/understanding-json-schema/
❏ Blog post -- https://elephantdolphin.blogspot.com/2019/07/json-schema-validation-with-mysql-
8017.html
25
Where to learn more
Copyright © 2020, Oracle and/or its affiliates | Confidential:
Internal/Restricted/Highly Restricted
26
Get $300 in credits
and try MySQL Database Service
free for 30 days.
https://www.oracle.com/cloud/free/
Test Drive MySQL Database Service For Free Today
Follow us on Social Media
27
MySQLCommunity.slack.com
Startups get cloud credits and a 70% discount for
2 years, global exposure via marketing, events,
digital promotion, and media, plus access to
mentorship, capital and Oracle’s 430,000+
customers
Customers meet vetted startups in transformative
spaces that help them stay ahead of their
competition
Oracle stays at the competitive edge
of innovation with solutions that complement its
technology stack
We have saved around 40% of our costs and are
able to reinvest that back into the business. And
we are scaling across EMEA, and that’s basically
all because of Oracle.”
—Asser Smidt
CEO and Cofounder, BotSupply
Oracle for Startups - enroll at oracle.com/startup
A Virtuous Cycle of Innovation, Everybody Wins.
28
Then please consider
buying my book on the
JSON data type, how to
use the supporting
functions, and it is filled
with example code to get
you up to speed!
Interested in using JSON with MySQL?
29
Thank You!
David.Stokes@oracle.com
@Stoker
slideshare.net/davestokes
30
Q&A
Validating JSON -- Percona Live 2021 presentation

More Related Content

What's hot (20)

PPTX
cPanel now supports MySQL 8.0 - My Top Seven Features
Dave Stokes
 
PDF
MySQL Replication Update - DEbconf 2020 presentation
Dave Stokes
 
PDF
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
Dave Stokes
 
PDF
MySQL 8.0 Operational Changes
Dave Stokes
 
PDF
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dave Stokes
 
PPTX
Confoo 2021 - MySQL Indexes & Histograms
Dave Stokes
 
PDF
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
PDF
Developing for Node.JS with MySQL and NoSQL
John David Duncan
 
PDF
My sql tutorial-oscon-2012
John David Duncan
 
PDF
Lecture17
vantinhkhuc
 
PDF
Cloudera Impala, updated for v1.0
Scott Leberknight
 
PPTX
Using Spark to Load Oracle Data into Cassandra
Jim Hatcher
 
PDF
Brief introduction of Slick
Knoldus Inc.
 
PPT
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Marco Gralike
 
PDF
20201106 hk-py con-mysql-shell
Ivan Ma
 
PPTX
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
Dave Stokes
 
PDF
MySQL without the SQL -- Cascadia PHP
Dave Stokes
 
PPT
XMLDB Building Blocks And Best Practices - Oracle Open World 2008 - Marco Gra...
Marco Gralike
 
PDF
Using JSON with MariaDB and MySQL
Anders Karlsson
 
PDF
Simple Jdbc With Spring 2.5
David Motta Baldarrago
 
cPanel now supports MySQL 8.0 - My Top Seven Features
Dave Stokes
 
MySQL Replication Update - DEbconf 2020 presentation
Dave Stokes
 
MySQL 8.0 New Features -- September 27th presentation for Open Source Summit
Dave Stokes
 
MySQL 8.0 Operational Changes
Dave Stokes
 
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
Dave Stokes
 
Confoo 2021 - MySQL Indexes & Histograms
Dave Stokes
 
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
Developing for Node.JS with MySQL and NoSQL
John David Duncan
 
My sql tutorial-oscon-2012
John David Duncan
 
Lecture17
vantinhkhuc
 
Cloudera Impala, updated for v1.0
Scott Leberknight
 
Using Spark to Load Oracle Data into Cassandra
Jim Hatcher
 
Brief introduction of Slick
Knoldus Inc.
 
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Marco Gralike
 
20201106 hk-py con-mysql-shell
Ivan Ma
 
PHP UK 2020 Tutorial: MySQL Indexes, Histograms And other ways To Speed Up Yo...
Dave Stokes
 
MySQL without the SQL -- Cascadia PHP
Dave Stokes
 
XMLDB Building Blocks And Best Practices - Oracle Open World 2008 - Marco Gra...
Marco Gralike
 
Using JSON with MariaDB and MySQL
Anders Karlsson
 
Simple Jdbc With Spring 2.5
David Motta Baldarrago
 

Similar to Validating JSON -- Percona Live 2021 presentation (20)

PDF
Store non-structured data in JSON column types and enhancements of JSON
Alireza Kamrani
 
PPTX
Starting with JSON Path Expressions in Oracle 12.1.0.2
Marco Gralike
 
PPTX
Oracle Database - JSON and the In-Memory Database
Marco Gralike
 
PDF
UKOUG Tech14 - Getting Started With JSON in the Database
Marco Gralike
 
PDF
MySQL JSON Functions
Sveta Smirnova
 
PDF
Moving to the NoSQL side: MySQL JSON functions
Sveta Smirnova
 
PPTX
JSON-SQLServer2016.pptx dgsdgdsgdsgdsgsdgdsgdsg
zmulani8
 
PPT
Using JSON/BSON types in your hybrid application environment
Ajay Gupte
 
PPTX
IBM Db2 JSON 11.5
Phil Downey
 
KEY
Devoxx - JSON Validation using JSON Schema and Jackson
Stephane Rondal
 
PDF
JSON in MySQL and MariaDB Databases
Federico Razzoli
 
PDF
JSON Data Parsing in Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
PDF
Second Step to the NoSQL Side: MySQL JSON Functions
Sveta Smirnova
 
PPTX
Sql Server 2016 and JSON
Greg McMurray
 
PPTX
The rise of json in rdbms land jab17
alikonweb
 
PDF
LF_APIStrat17_Embracing JSON Schema
LF_APIStrat
 
PDF
MySQL 5.7 + JSON
Morgan Tocker
 
PPTX
Power JSON with PostgreSQL
EDB
 
PDF
NoSQL атакует: JSON функции в MySQL сервере.
Sveta Smirnova
 
PDF
MySQL's JSON Data Type and Document Store
Dave Stokes
 
Store non-structured data in JSON column types and enhancements of JSON
Alireza Kamrani
 
Starting with JSON Path Expressions in Oracle 12.1.0.2
Marco Gralike
 
Oracle Database - JSON and the In-Memory Database
Marco Gralike
 
UKOUG Tech14 - Getting Started With JSON in the Database
Marco Gralike
 
MySQL JSON Functions
Sveta Smirnova
 
Moving to the NoSQL side: MySQL JSON functions
Sveta Smirnova
 
JSON-SQLServer2016.pptx dgsdgdsgdsgdsgsdgdsgdsg
zmulani8
 
Using JSON/BSON types in your hybrid application environment
Ajay Gupte
 
IBM Db2 JSON 11.5
Phil Downey
 
Devoxx - JSON Validation using JSON Schema and Jackson
Stephane Rondal
 
JSON in MySQL and MariaDB Databases
Federico Razzoli
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
Second Step to the NoSQL Side: MySQL JSON Functions
Sveta Smirnova
 
Sql Server 2016 and JSON
Greg McMurray
 
The rise of json in rdbms land jab17
alikonweb
 
LF_APIStrat17_Embracing JSON Schema
LF_APIStrat
 
MySQL 5.7 + JSON
Morgan Tocker
 
Power JSON with PostgreSQL
EDB
 
NoSQL атакует: JSON функции в MySQL сервере.
Sveta Smirnova
 
MySQL's JSON Data Type and Document Store
Dave Stokes
 
Ad

More from Dave Stokes (15)

PDF
Database basics for new-ish developers -- All Things Open October 18th 2021
Dave Stokes
 
PDF
Midwest PHP Presentation - New MSQL Features
Dave Stokes
 
PDF
Data Love Conference - Window Functions for Database Analytics
Dave Stokes
 
PPTX
Confoo 2021 -- MySQL New Features
Dave Stokes
 
PPTX
A Step by Step Introduction to the MySQL Document Store
Dave Stokes
 
PPTX
Discover The Power of NoSQL + MySQL with MySQL
Dave Stokes
 
PDF
Confoo 202 - MySQL Group Replication and ReplicaSet
Dave Stokes
 
PDF
MySQL New Features -- Sunshine PHP 2020 Presentation
Dave Stokes
 
PPTX
MySQL 8.0 from December London Open Source Database Meetup
Dave Stokes
 
PPTX
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
Dave Stokes
 
PPTX
Upgrading to MySQL 8.0 webinar slides November 27th, 2019
Dave Stokes
 
PDF
Windowing Functions - Little Rock Tech Fest 2019
Dave Stokes
 
PDF
Oracle CodeOne Foreign Keys Support in MySQL 8.0
Dave Stokes
 
PDF
MySQL Without the SQL - Oh My! August 2nd presentation at Mid Atlantic Develo...
Dave Stokes
 
PDF
MySQL 8.0 Graphical Information System - Mid Atlantic Developers Conference
Dave Stokes
 
Database basics for new-ish developers -- All Things Open October 18th 2021
Dave Stokes
 
Midwest PHP Presentation - New MSQL Features
Dave Stokes
 
Data Love Conference - Window Functions for Database Analytics
Dave Stokes
 
Confoo 2021 -- MySQL New Features
Dave Stokes
 
A Step by Step Introduction to the MySQL Document Store
Dave Stokes
 
Discover The Power of NoSQL + MySQL with MySQL
Dave Stokes
 
Confoo 202 - MySQL Group Replication and ReplicaSet
Dave Stokes
 
MySQL New Features -- Sunshine PHP 2020 Presentation
Dave Stokes
 
MySQL 8.0 from December London Open Source Database Meetup
Dave Stokes
 
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
Dave Stokes
 
Upgrading to MySQL 8.0 webinar slides November 27th, 2019
Dave Stokes
 
Windowing Functions - Little Rock Tech Fest 2019
Dave Stokes
 
Oracle CodeOne Foreign Keys Support in MySQL 8.0
Dave Stokes
 
MySQL Without the SQL - Oh My! August 2nd presentation at Mid Atlantic Develo...
Dave Stokes
 
MySQL 8.0 Graphical Information System - Mid Atlantic Developers Conference
Dave Stokes
 
Ad

Recently uploaded (20)

PDF
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
PPTX
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PPTX
PE introd.pptxfrgfgfdgfdgfgrtretrt44t444
nepmithibai2024
 
PPT
introductio to computers by arthur janry
RamananMuthukrishnan
 
PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
PDF
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
PPTX
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
PPT
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PPTX
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
PPTX
英国假毕业证诺森比亚大学成绩单GPA修改UNN学生卡网上可查学历成绩单
Taqyea
 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PPTX
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PDF
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
 
PDF
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PE introd.pptxfrgfgfdgfdgfgrtretrt44t444
nepmithibai2024
 
introductio to computers by arthur janry
RamananMuthukrishnan
 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
Computer Securityyyyyyyy - Chapter 2.ppt
SolomonSB
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
英国假毕业证诺森比亚大学成绩单GPA修改UNN学生卡网上可查学历成绩单
Taqyea
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
The-Hidden-Dangers-of-Skipping-Penetration-Testing.pdf.pdf
naksh4thra
 
introduction to networking with basics coverage
RamananMuthukrishnan
 
AI_MOD_1.pdf artificial intelligence notes
shreyarrce
 

Validating JSON -- Percona Live 2021 presentation

  • 1. JSON Validation Dave Stokes MySQL Community Manager MySQL Community Team
  • 2. Dave Stokes MySQL Community Team Oracle Corporation @Stoker https://elephantdolphin.blogspot.com/ [email protected] Slides are available at Slideshare.net/davestokes 2
  • 3. 3 JSON JSON (JavaScript Object Notation is an open standard file format, and data interchange format, that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value). It is a very common data format, with a diverse range of applications, such as serving as a replacement for XML in AJAX systems. JSON is a language-independent data format. It was derived from JavaScript, but many modern programming languages include code to generate and parse JSON-format data -- https://en.wikipedia.org/wiki/JSON
  • 4. { "GNP": 8510700, "_id": "USA", "Name": "United States", "IndepYear": 1776, "geography": { "Region": "North America", "Continent": "North America", "SurfaceArea": 9363520 }, "government": { "HeadOfState": "George W. Bush", "GovernmentForm": "Federal Republic" }, "demographics": { "Population": 278357000, "LifeExpectancy": 77.0999984741211 } } 4 What does JSON look like?
  • 5. { "GNP": 8510700, "_id": "USA", "Name": "United States", "IndepYear": 1776, "geography": { "Region": "North America", "Continent": "North America", "SurfaceArea": 9363520 }, "government": { "HeadOfState": "George W. Bush", "GovernmentForm": "Federal Republic" }, "demographics": { "Population": 278357000, "LifeExpectancy": 77.0999984741211 } } 5 What does JSON look like? KEY : VALUE
  • 6. { "GNP": 8510700, "_id": "USA", "Name": "United States", "IndepYear": 1776, "geography": { "Region": "North America", "Continent": "North America", "SurfaceArea": 9363520 }, "government": { "HeadOfState": "George W. Bush", "GovernmentForm": "Federal Republic" }, "demographics": { "Population": 278357000, "LifeExpectancy": 77.0999984741211 } } 6 What does JSON look like? Document enclosed in brackets {}
  • 7. OBJECTS are enclosed in {} JSON: OBJECTS versus ARRAYS 7 Arrays are enclosed in []
  • 9. Strict data types INT, CHAR, DECIMAL, etc. Optional Required columns Default Values Constraint Checks, including range Relational Databases 9 All these features can enforce rigor on you data to ensure that it is properly formatted BEFORE it gets saved in the database. BTW - Much less expensive to keep bad data out than having to correct it later!
  • 11. JSON’s Freeform Can hurt How would you save email address? email: [email protected] eMail: [email protected] e-mail: [email protected] electronicMail: [email protected] EMail: [email protected] eMaIl: [email protected] Each of the keys here are unique and valid Searching for email addresses would require being able to look for all the forms! 11
  • 12. 12 Some Examples of keeping data clean create table percona (id int, name char(25)); insert into percona values ('test'); ERROR: 1136: Column count doesn't match value count at row 1 CREATE table pz (id int, name char(25) not null); insert into pz (id) values (1); ERROR: 1364: Field 'name' doesn't have a default value CREATE TABLE check_plz ( c1 int constraint c1_not_42_error check (c1 <> 42) default 42, c2 int default 42); Query OK, 0 rows affected (0.2902 sec) insert into check_plz (c2) values(NULL); ERROR: 3819: Check constraint 'c1_not_42_error' is violated.
  • 13. 13 But what if there was a way to check JSON data?
  • 14. 14
  • 15. 15
  • 16. 16 The Functions JSON_SCHEMA_VALID(schema,document) Validates a JSON document against a JSON schema. Both schema and document are required. The schema must be a valid JSON object; the document must be a valid JSON document. Provided that these conditions are met: If the document validates against the schema, the function returns true (1); otherwise, it returns false (0).
  • 17. 17 The Functions JSON_SCHEMA_VALIDATION_REPORT(schema,document) Validates a JSON document against a JSON schema.The schema must be a valid JSON object, and the document must be a valid JSON document. Provided that these conditions are met, the function returns a report, as a JSON document, on the outcome of the validation. If the JSON document is considered valid according to the JSON Schema, the function returns a JSON object with one property valid having the value "true". If the JSON document fails validation, the function returns a JSON object which includes the properties listed here: ○ valid: Always "false" for a failed schema validation ○ reason: A human-readable string containing the reason for the failure ○ schema-location: A JSON pointer URI fragment identifier indicating where in the JSON schema the validation failed (see Note following this list) ○ document-location: A JSON pointer URI fragment identifier indicating where in the JSON document the validation failed (see Note following this list) ○ schema-failed-keyword: A string containing the name of the keyword or property in the JSON schema that was violated
  • 18. 18 Simple Example 1 -- the exemplar, the new document, and the test set @s='{"type": "object", "properties": { "myage": { "type" : "number", "minimum": 28, "maximum": 99 } } }'; set @d='{ "myage": 33}' select JSON_SCHEMA_VALID(@s,@d); +--------------------------+ | JSON_SCHEMA_VALID(@s,@d) | +--------------------------+ | 1 | +--------------------------+ 1 row in set (0.00 sec)
  • 19. 19 Simple Example 2 -- the exemplar, the new document, and the test set @s='{"type": "object", "properties": { "myage": { "type" : "number", "minimum": 28, "maximum": 99 } } }'; set @d='{ "myage": “foo”}' select JSON_SCHEMA_VALID(@s,@d); +--------------------------+ | JSON_SCHEMA_VALID(@s,@d) | +--------------------------+ | 0 | +--------------------------+ 1 row in set (0.00 sec)
  • 20. 20 Simple Example 3 -- the exemplar, the new document, and the test set @s='{"type": "object", "properties": { "myage": { "type" : "number", "minimum": 28, "maximum": 99 } } }'; set @d='{ "myage": 16}' select JSON_SCHEMA_VALID(@s,@d); +--------------------------+ | JSON_SCHEMA_VALID(@s,@d) | +--------------------------+ | 0 | +--------------------------+ 1 row in set (0.00 sec)
  • 21. select JSON_PRETTY(JSON_SCHEMA_VALIDATION_REPORT(@s,@d))G *************************** 1. row *************************** JSON_PRETTY(JSON_SCHEMA_VALIDATION_REPORT(@s,@d)): { "valid": false, "reason": "The JSON document location '#/myage' failed requirement 'minimum' at JSON Schema location '#/properties/myage'", "schema-location": "#/properties/myage", "document-location": "#/myage", "schema-failed-keyword": "minimum" } JSON_SCHEMA_VALIDATION_REPORT() 21
  • 22. CREATE TABLE `testx` ( `col` JSON, CONSTRAINT `myage_inRange` CHECK (JSON_SCHEMA_VALID('{"type": "object", "properties": { "myage": { "type" : "number", "minimum": 28, "maximum": 99 } },"required": ["myage"] }', `col`) = 1) ); REQUIRE Fields 22
  • 23. CREATE TABLE `testx` ( `col` JSON, CONSTRAINT `myage_inRange` CHECK (JSON_SCHEMA_VALID('{"type": "object", "properties": { "myage": { "type" : "number", "minimum": 28, "maximum": 99 } },"required": ["myage"] }', `col`) = 1) ); REQUIRE Fields 23 insert into testx values('{"myage":27}'); ERROR 3819 (HY000): Check constraint 'myage_inRange' is violated. insert into testx values('{"myage":97}'); Query OK, 1 row affected (0.02 sec)
  • 24. 24
  • 25. ❏ MySQL Manual -- https://dev.mysql.com/doc/refman/8.0/en/json-validation-functions.html ❏ Understanding JSON Schema -- http://json-schema.org/understanding-json-schema/ ❏ Blog post -- https://elephantdolphin.blogspot.com/2019/07/json-schema-validation-with-mysql- 8017.html 25 Where to learn more
  • 26. Copyright © 2020, Oracle and/or its affiliates | Confidential: Internal/Restricted/Highly Restricted 26 Get $300 in credits and try MySQL Database Service free for 30 days. https://www.oracle.com/cloud/free/ Test Drive MySQL Database Service For Free Today
  • 27. Follow us on Social Media 27 MySQLCommunity.slack.com
  • 28. Startups get cloud credits and a 70% discount for 2 years, global exposure via marketing, events, digital promotion, and media, plus access to mentorship, capital and Oracle’s 430,000+ customers Customers meet vetted startups in transformative spaces that help them stay ahead of their competition Oracle stays at the competitive edge of innovation with solutions that complement its technology stack We have saved around 40% of our costs and are able to reinvest that back into the business. And we are scaling across EMEA, and that’s basically all because of Oracle.” —Asser Smidt CEO and Cofounder, BotSupply Oracle for Startups - enroll at oracle.com/startup A Virtuous Cycle of Innovation, Everybody Wins. 28
  • 29. Then please consider buying my book on the JSON data type, how to use the supporting functions, and it is filled with example code to get you up to speed! Interested in using JSON with MySQL? 29