SlideShare a Scribd company logo
1 of 26
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
PGDay UK 2013
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
12th July 2013
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
Overview
● XML
– XML Primer
– History of XML in PostgreSQL
– Using PostgreSQL's XML features
● JSON
– JSON Primer
– History of JSON in PostgreSQL
– Using PostgreSQL's JSON features
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
About Me
● Been using PostgreSQL for ~10 years
● Contributed some XML support
– XMLEXISTS/xpath_exists()
– xml_is_well_formed()
● Buildfarm member piapiac
– Amazon EC2 based build for JDBC driver
– Has lead to a number of bugfix patches for JDBC
http://www.pgbuildfarm.org/cgi-bin/show_status.pl?
member=piapiac
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
Reasons to store XML/JSON
● Client application uses it
– Configuration
– Serialised objects
● Data format/schema is highly complex/variable
● You just don't “care” about the data!
– Audit data
– Application log files
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
Primer: XML
● eXtensible Markup Language
● Human readable data interchange &
serialisation format
● Consists of a root element containing a mix of
child elements and text content with any
element having optional attributes
<root>
<child attribute=”value”>
text based content
</child>
</root>
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML Support
● ANSI and ISO standards exist
– Introduced in SQL/XML 2003
– Augmented in SQL/XML 2006
● Prior to 8.3 XML support was a contrib module
● Added to core in 8.3 but remains a compile
time option enabled with:
configure --with-libxml
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML Support
● xml datatype (internally stored as text)
● Keywords from the standards
– DOCUMENT, CONTENT
– XMLPARSE, XMLSERIALIZE ...
● Predicates, also from the standards
– IS [NOT] DOCUMENT
– XMLEXISTS (9.1)
● A number of support functions, not standard
– xmlconcat(), xpath() ...
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: The Hard Way
● Using “standard” SQL, XML is inserted:
INSERT INTO demo (data) VALUES (XMLPARSE (DOCUMENT '<?
xml version="1.0"?> <book> <title>Manual</title>
<chapter>...</chapter> </book>'))
● To retrieve using “standard” SQL:
SELECT XMLSERIALIZE(DOCUMENT data AS text) FROM ...
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: The Easy Way
● It's a normal datatype, use normal casting!
● INSERT (::xml is optional as text will
implicitly cast to xml even in 9.3)
pgday=# INSERT INTO demo (data) VALUES ('<?xml
version="1.0"?> pgday-# <book> <title>Manual</title>
pgday-# <chapter>...</chapter> </book>'::xml);
INSERT 0 1
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: The Easy Way
● SELECT (::text is optional as far as
rendering in the psql client is concerned)
pgday=# SELECT data::text FROM demo WHERE ...
data
----------------------------------------------------------
<book><title>Manual</title><chapter>...</chapter></book>
(1 row)
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: xmloption
● When casting without XMLPARSE or
XMLSERIALIZE the choice of DOCUMENT or
CONTENT is determined by the value of the 'XML
option' session variable
SET XML OPTION { DOCUMENT | CONTENT}
SET xmloption TO { DOCUMENT |
CONTENT}
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: Predicates
● IS DOCUMENT / IS NOT DOCUMENT
– Use to filter between DOCUMENT and CONTENT
– Only works with data that is already cast as XML
pgday=# SELECT XMLSERIALIZE(DOCUMENT data AS text)
FROM
pgday-# WHERE data IS DOCUMENT;
pgday=# SELECT XMLSERIALIZE(CONTENT data AS text)
FROM
pgday-# WHERE data IS NOT DOCUMENT;
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: Predicates
● xml_is_well_formed()
– Introduced in 9.1 and takes text as a parameter
– Sensitive to XMLOPTION
● SET xmloption DOCUMENT;
– Also xml_is_well_formed_documet() and
xml_is_well_formed_content()
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: xpath()
xpath(xpath, xml [, nsarray])
● Allows you to extract elements and text
● Supports namespaces
● Returns an array of XML
● Also returns empty arrays when there is no match
SELECT xpath('//title/text()',data)
FROM ...
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: XMLEXISTS
XMLEXISTS(text PASSING [BY REF] xml [BY REF])
● From the standard, useful for predicates
● First parameter is an xpath expression
SELECT xpath('//title/text()',data)
FROM demo WHERE XMLEXISTS('//title'
PASSING data);
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
XML: xpath_exists()
xpath_exists(xpath, xml [, nsarray])
● Serves the same purpose as XMLEXISTS but:
– Supports namespaces
– Syntax is simplier
SELECT xpath('//title/text()',data)
FROM demo WHERE
xpath_exists('//title', data);
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
Primer: JSON
● JavaScript Object Notation
● Also a human readable data interchange &
serialisation format
● { } denote objects containing a comma
separated list of name value pairs where
values can be nested objects or arrays
{
“name”:”value”,
“nestedObject”: {
“array”:[“value1”,”value2”]
},
“numeric”:13
}
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
JSON Support
● Not a SQL standard
● PostgreSQL is currently the only RDBMS with
native support
● Design borrows heavily from PostgreSQL's
existing XML support
– Internal storage format is TEXT
– Basic validation (e.g. well formed)
● Does not require special libraries to enable
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
JSON Support
● Basic support introduced in 9.2
– JSON datatype
– 2 support functions
● row_to_json()
● array_to_json()
● Operators and additional functions in 9.3
– ->,->>,#>,#>>
– 10 more support functions
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
JSON Support
● INSERT always ensures type validity
pgday=# INSERT INTO demo VALUES
pgday-# ('{"name":"Mike","hungry":true}');
INSERT 0 1
pgday=# INSERT INTO demo VALUES
pgday-# ('{"name":"Mike",hungry:true}');
ERROR: invalid input syntax for type json at
character 28
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
JSON: Operators
● Retrieve the value of an attribute
SELECT data->'name' AS name FROM …
● Use the value of an attribute in a predicate
SELECT data FROM demo WHERE
data->>'name' = 'Mike';
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
JSON: Functions
row_to_json(record [, pretty_bool])
Returns a result set where each row is a JSON object
pgday=# SELECT * FROM demo;
username | posts | email
----------+-------+-------------------
mlfowler | 121 | mike@mlfowler.com
fowlerm | 9 | mike@work.com
pgday=# SELECT row_to_json(demo) FROM demo;
row_to_json
-----------------------------------------------------------------
{"username":"mlfowler","posts":121,"email":"mike@mlfowler.com"}
{"username":"fowlerm","posts":9,"email":"mike@work.com"}
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
JSON: Functions
json_object_keys(json)
Returns all the keys in the top level
pgday=# SELECT json_object_keys(data) FROM demo;
json_object_keys
------------------
name
hungry
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
Caveats
● They are not indexable
– You will need to plan how best to retrieve
● Best used programmaticly
– Syntax of XML and JSON can be unwieldy
● Non-UTF8 encoded databases
● Not portable
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
Summary
● Using the PostgreSQL XML and JSON
datatypes allows you finer control of an
otherwise free format field
● PostgreSQL's XML non-standard support is
much easier to use than the standard
● JSON is still being very actively developed
Handling XML and JSON in the Database
Mike Fowler, mike@mlfowler.com
PGDayUK 2013
Thank you!
Mike Fowler
mike@mlfowler.com

More Related Content

What's hot

Group Replication in MySQL 8.0 ( A Walk Through )
Group Replication in MySQL 8.0 ( A Walk Through ) Group Replication in MySQL 8.0 ( A Walk Through )
Group Replication in MySQL 8.0 ( A Walk Through ) Mydbops
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slidesmetsarin
 
Los Angeles R users group - Dec 14 2010 - Part 2
Los Angeles R users group - Dec 14 2010 - Part 2Los Angeles R users group - Dec 14 2010 - Part 2
Los Angeles R users group - Dec 14 2010 - Part 2rusersla
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerMydbops
 
34 using mysql with java
34 using mysql with java34 using mysql with java
34 using mysql with java果 果
 
9780538745840 ppt ch07
9780538745840 ppt ch079780538745840 ppt ch07
9780538745840 ppt ch07Terry Yoast
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaEdureka!
 
A brief introduction to PostgreSQL
A brief introduction to PostgreSQLA brief introduction to PostgreSQL
A brief introduction to PostgreSQLVu Hung Nguyen
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xqueryAmol Pujari
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQLNicole Ryan
 
3.1\9 SSIS 2008R2_Training - ControlFlow asks
3.1\9 SSIS 2008R2_Training - ControlFlow asks3.1\9 SSIS 2008R2_Training - ControlFlow asks
3.1\9 SSIS 2008R2_Training - ControlFlow asksPramod Singla
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An IntroductionSmita Prasad
 
SQL – A Tutorial I
SQL – A Tutorial  ISQL – A Tutorial  I
SQL – A Tutorial IGagan Deep
 
Language enhancements in cold fusion 11
Language enhancements in cold fusion 11Language enhancements in cold fusion 11
Language enhancements in cold fusion 11ColdFusionConference
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With MysqlHarit Kothari
 

What's hot (20)

Group Replication in MySQL 8.0 ( A Walk Through )
Group Replication in MySQL 8.0 ( A Walk Through ) Group Replication in MySQL 8.0 ( A Walk Through )
Group Replication in MySQL 8.0 ( A Walk Through )
 
PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Los Angeles R users group - Dec 14 2010 - Part 2
Los Angeles R users group - Dec 14 2010 - Part 2Los Angeles R users group - Dec 14 2010 - Part 2
Los Angeles R users group - Dec 14 2010 - Part 2
 
Introduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizerIntroduction to Mongodb execution plan and optimizer
Introduction to Mongodb execution plan and optimizer
 
34 using mysql with java
34 using mysql with java34 using mysql with java
34 using mysql with java
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
 
9780538745840 ppt ch07
9780538745840 ppt ch079780538745840 ppt ch07
9780538745840 ppt ch07
 
PostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | EdurekaPostgreSQL Tutorial For Beginners | Edureka
PostgreSQL Tutorial For Beginners | Edureka
 
Introduction to php database connectivity
Introduction to php  database connectivityIntroduction to php  database connectivity
Introduction to php database connectivity
 
A brief introduction to PostgreSQL
A brief introduction to PostgreSQLA brief introduction to PostgreSQL
A brief introduction to PostgreSQL
 
Sqlxml vs xquery
Sqlxml vs xquerySqlxml vs xquery
Sqlxml vs xquery
 
Working with Databases and MySQL
Working with Databases and MySQLWorking with Databases and MySQL
Working with Databases and MySQL
 
DB2 Native XML
DB2 Native XMLDB2 Native XML
DB2 Native XML
 
3.1\9 SSIS 2008R2_Training - ControlFlow asks
3.1\9 SSIS 2008R2_Training - ControlFlow asks3.1\9 SSIS 2008R2_Training - ControlFlow asks
3.1\9 SSIS 2008R2_Training - ControlFlow asks
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An Introduction
 
SQL – A Tutorial I
SQL – A Tutorial  ISQL – A Tutorial  I
SQL – A Tutorial I
 
Language enhancements in cold fusion 11
Language enhancements in cold fusion 11Language enhancements in cold fusion 11
Language enhancements in cold fusion 11
 
MYSQL-Database
MYSQL-DatabaseMYSQL-Database
MYSQL-Database
 
Database Connection With Mysql
Database Connection With MysqlDatabase Connection With Mysql
Database Connection With Mysql
 

Viewers also liked

Migrating Rant & Rave to PostgreSQL
Migrating Rant & Rave to PostgreSQLMigrating Rant & Rave to PostgreSQL
Migrating Rant & Rave to PostgreSQLMike Fowler
 
Fun Things to do with Logical Decoding
Fun Things to do with Logical DecodingFun Things to do with Logical Decoding
Fun Things to do with Logical DecodingMike Fowler
 
Disposable infrastructure
Disposable infrastructureDisposable infrastructure
Disposable infrastructureMike Fowler
 
African Americans: College Majors and Earnings
African Americans: College Majors and Earnings African Americans: College Majors and Earnings
African Americans: College Majors and Earnings CEW Georgetown
 
The Online College Labor Market
The Online College Labor MarketThe Online College Labor Market
The Online College Labor MarketCEW Georgetown
 
Teaching Students with Emojis, Emoticons, & Textspeak
Teaching Students with Emojis, Emoticons, & TextspeakTeaching Students with Emojis, Emoticons, & Textspeak
Teaching Students with Emojis, Emoticons, & TextspeakShelly Sanchez Terrell
 
GAME ON! Integrating Games and Simulations in the Classroom
GAME ON! Integrating Games and Simulations in the Classroom GAME ON! Integrating Games and Simulations in the Classroom
GAME ON! Integrating Games and Simulations in the Classroom Brian Housand
 
Responding to Academically Distressed Students
Responding to Academically Distressed StudentsResponding to Academically Distressed Students
Responding to Academically Distressed StudentsMr. Ronald Quileste, PhD
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsLinkedIn
 
Dear NSA, let me take care of your slides.
Dear NSA, let me take care of your slides.Dear NSA, let me take care of your slides.
Dear NSA, let me take care of your slides.Emiland
 
What I Carry: 10 Tools for Success
What I Carry: 10 Tools for SuccessWhat I Carry: 10 Tools for Success
What I Carry: 10 Tools for SuccessJonathon Colman
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesNed Potter
 
Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging ChallengesAaron Irizarry
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with DataSeth Familian
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017Drift
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheLeslie Samuel
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShareSlideShare
 

Viewers also liked (18)

Migrating Rant & Rave to PostgreSQL
Migrating Rant & Rave to PostgreSQLMigrating Rant & Rave to PostgreSQL
Migrating Rant & Rave to PostgreSQL
 
Fun Things to do with Logical Decoding
Fun Things to do with Logical DecodingFun Things to do with Logical Decoding
Fun Things to do with Logical Decoding
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
Disposable infrastructure
Disposable infrastructureDisposable infrastructure
Disposable infrastructure
 
African Americans: College Majors and Earnings
African Americans: College Majors and Earnings African Americans: College Majors and Earnings
African Americans: College Majors and Earnings
 
The Online College Labor Market
The Online College Labor MarketThe Online College Labor Market
The Online College Labor Market
 
Teaching Students with Emojis, Emoticons, & Textspeak
Teaching Students with Emojis, Emoticons, & TextspeakTeaching Students with Emojis, Emoticons, & Textspeak
Teaching Students with Emojis, Emoticons, & Textspeak
 
GAME ON! Integrating Games and Simulations in the Classroom
GAME ON! Integrating Games and Simulations in the Classroom GAME ON! Integrating Games and Simulations in the Classroom
GAME ON! Integrating Games and Simulations in the Classroom
 
Responding to Academically Distressed Students
Responding to Academically Distressed StudentsResponding to Academically Distressed Students
Responding to Academically Distressed Students
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 
Dear NSA, let me take care of your slides.
Dear NSA, let me take care of your slides.Dear NSA, let me take care of your slides.
Dear NSA, let me take care of your slides.
 
What I Carry: 10 Tools for Success
What I Carry: 10 Tools for SuccessWhat I Carry: 10 Tools for Success
What I Carry: 10 Tools for Success
 
UX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and ArchivesUX, ethnography and possibilities: for Libraries, Museums and Archives
UX, ethnography and possibilities: for Libraries, Museums and Archives
 
Designing Teams for Emerging Challenges
Designing Teams for Emerging ChallengesDesigning Teams for Emerging Challenges
Designing Teams for Emerging Challenges
 
Visual Design with Data
Visual Design with DataVisual Design with Data
Visual Design with Data
 
3 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 20173 Things Every Sales Team Needs to Be Thinking About in 2017
3 Things Every Sales Team Needs to Be Thinking About in 2017
 
How to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your NicheHow to Become a Thought Leader in Your Niche
How to Become a Thought Leader in Your Niche
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 

Similar to Handling XML and JSON in the Database

Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Marco Gralike
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architectureGabriele Falace
 
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1Marco Gralike
 
Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeBoost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeMarco Gralike
 
XML Support: Specifications and Development
XML Support: Specifications and DevelopmentXML Support: Specifications and Development
XML Support: Specifications and DevelopmentPeter Eisentraut
 
Ml pipelines with Apache spark and Apache beam - Ottawa Reactive meetup Augus...
Ml pipelines with Apache spark and Apache beam - Ottawa Reactive meetup Augus...Ml pipelines with Apache spark and Apache beam - Ottawa Reactive meetup Augus...
Ml pipelines with Apache spark and Apache beam - Ottawa Reactive meetup Augus...Holden Karau
 
Pxb For Yapc2008
Pxb For Yapc2008Pxb For Yapc2008
Pxb For Yapc2008maximgrp
 
JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0Mydbops
 
SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLJerry Yang
 
Json improvements in my sql 8.0
Json improvements in my sql 8.0  Json improvements in my sql 8.0
Json improvements in my sql 8.0 Mysql User Camp
 
Tour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTatu Saloranta
 
soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6soft-shake.ch
 

Similar to Handling XML and JSON in the Database (20)

Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
Real World Experience With Oracle Xml Database 11g An Oracle Ace’s Perspectiv...
 
AngularJS application architecture
AngularJS application architectureAngularJS application architecture
AngularJS application architecture
 
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
OPP2010 (Brussels) - Programming with XML in PL/SQL - Part 1
 
Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco GralikeBoost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
Boost Your Environment With XMLDB - UKOUG 2008 - Marco Gralike
 
XML Support: Specifications and Development
XML Support: Specifications and DevelopmentXML Support: Specifications and Development
XML Support: Specifications and Development
 
Ml pipelines with Apache spark and Apache beam - Ottawa Reactive meetup Augus...
Ml pipelines with Apache spark and Apache beam - Ottawa Reactive meetup Augus...Ml pipelines with Apache spark and Apache beam - Ottawa Reactive meetup Augus...
Ml pipelines with Apache spark and Apache beam - Ottawa Reactive meetup Augus...
 
Pxb For Yapc2008
Pxb For Yapc2008Pxb For Yapc2008
Pxb For Yapc2008
 
JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0JSON improvements in MySQL 8.0
JSON improvements in MySQL 8.0
 
SQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQLSQL Server 2000 Research Series - Transact SQL
SQL Server 2000 Research Series - Transact SQL
 
Erik_van_Roon.pdf
Erik_van_Roon.pdfErik_van_Roon.pdf
Erik_van_Roon.pdf
 
9.4json
9.4json9.4json
9.4json
 
Json improvements in my sql 8.0
Json improvements in my sql 8.0  Json improvements in my sql 8.0
Json improvements in my sql 8.0
 
Tour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processorTour de Jackson: Forgotten Features of Jackson JSON processor
Tour de Jackson: Forgotten Features of Jackson JSON processor
 
R-XML.docx
R-XML.docxR-XML.docx
R-XML.docx
 
R-XML.docx
R-XML.docxR-XML.docx
R-XML.docx
 
XML parsing using jaxb
XML parsing using jaxbXML parsing using jaxb
XML parsing using jaxb
 
soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6soft-shake.ch - JAX-RS and Java EE 6
soft-shake.ch - JAX-RS and Java EE 6
 
An Introduction to Postgresql
An Introduction to PostgresqlAn Introduction to Postgresql
An Introduction to Postgresql
 
2310 b 12
2310 b 122310 b 12
2310 b 12
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 

More from Mike Fowler

From Warehouses to Lakes: The Value of Streams
From Warehouses to Lakes: The Value of StreamsFrom Warehouses to Lakes: The Value of Streams
From Warehouses to Lakes: The Value of StreamsMike Fowler
 
From Warehouses to Lakes: The Value of Streams
From Warehouses to Lakes: The Value of StreamsFrom Warehouses to Lakes: The Value of Streams
From Warehouses to Lakes: The Value of StreamsMike Fowler
 
Getting Started with Machine Learning on AWS
Getting Started with Machine Learning on AWSGetting Started with Machine Learning on AWS
Getting Started with Machine Learning on AWSMike Fowler
 
Building with Firebase
Building with FirebaseBuilding with Firebase
Building with FirebaseMike Fowler
 
Reducing Pager Fatigue Using a Serverless ML Bot
Reducing Pager Fatigue Using a Serverless ML BotReducing Pager Fatigue Using a Serverless ML Bot
Reducing Pager Fatigue Using a Serverless ML BotMike Fowler
 
Getting started with Machine Learning
Getting started with Machine LearningGetting started with Machine Learning
Getting started with Machine LearningMike Fowler
 
Migrating with Debezium
Migrating with DebeziumMigrating with Debezium
Migrating with DebeziumMike Fowler
 
Leveraging Automation for a Disposable Infrastructure
Leveraging Automation for a Disposable InfrastructureLeveraging Automation for a Disposable Infrastructure
Leveraging Automation for a Disposable InfrastructureMike Fowler
 
Migrating PostgreSQL to the Cloud
Migrating PostgreSQL to the CloudMigrating PostgreSQL to the Cloud
Migrating PostgreSQL to the CloudMike Fowler
 
Shaping Clouds with Terraform
Shaping Clouds with TerraformShaping Clouds with Terraform
Shaping Clouds with TerraformMike Fowler
 
Elephants in the Cloud
Elephants in the CloudElephants in the Cloud
Elephants in the CloudMike Fowler
 
Google Cloud & Your Data
Google Cloud & Your DataGoogle Cloud & Your Data
Google Cloud & Your DataMike Fowler
 
Hosted PostgreSQL
Hosted PostgreSQLHosted PostgreSQL
Hosted PostgreSQLMike Fowler
 

More from Mike Fowler (13)

From Warehouses to Lakes: The Value of Streams
From Warehouses to Lakes: The Value of StreamsFrom Warehouses to Lakes: The Value of Streams
From Warehouses to Lakes: The Value of Streams
 
From Warehouses to Lakes: The Value of Streams
From Warehouses to Lakes: The Value of StreamsFrom Warehouses to Lakes: The Value of Streams
From Warehouses to Lakes: The Value of Streams
 
Getting Started with Machine Learning on AWS
Getting Started with Machine Learning on AWSGetting Started with Machine Learning on AWS
Getting Started with Machine Learning on AWS
 
Building with Firebase
Building with FirebaseBuilding with Firebase
Building with Firebase
 
Reducing Pager Fatigue Using a Serverless ML Bot
Reducing Pager Fatigue Using a Serverless ML BotReducing Pager Fatigue Using a Serverless ML Bot
Reducing Pager Fatigue Using a Serverless ML Bot
 
Getting started with Machine Learning
Getting started with Machine LearningGetting started with Machine Learning
Getting started with Machine Learning
 
Migrating with Debezium
Migrating with DebeziumMigrating with Debezium
Migrating with Debezium
 
Leveraging Automation for a Disposable Infrastructure
Leveraging Automation for a Disposable InfrastructureLeveraging Automation for a Disposable Infrastructure
Leveraging Automation for a Disposable Infrastructure
 
Migrating PostgreSQL to the Cloud
Migrating PostgreSQL to the CloudMigrating PostgreSQL to the Cloud
Migrating PostgreSQL to the Cloud
 
Shaping Clouds with Terraform
Shaping Clouds with TerraformShaping Clouds with Terraform
Shaping Clouds with Terraform
 
Elephants in the Cloud
Elephants in the CloudElephants in the Cloud
Elephants in the Cloud
 
Google Cloud & Your Data
Google Cloud & Your DataGoogle Cloud & Your Data
Google Cloud & Your Data
 
Hosted PostgreSQL
Hosted PostgreSQLHosted PostgreSQL
Hosted PostgreSQL
 

Recently uploaded

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Recently uploaded (20)

Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Handling XML and JSON in the Database

  • 1. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 PGDay UK 2013 Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com 12th July 2013
  • 2. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 Overview ● XML – XML Primer – History of XML in PostgreSQL – Using PostgreSQL's XML features ● JSON – JSON Primer – History of JSON in PostgreSQL – Using PostgreSQL's JSON features
  • 3. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 About Me ● Been using PostgreSQL for ~10 years ● Contributed some XML support – XMLEXISTS/xpath_exists() – xml_is_well_formed() ● Buildfarm member piapiac – Amazon EC2 based build for JDBC driver – Has lead to a number of bugfix patches for JDBC http://www.pgbuildfarm.org/cgi-bin/show_status.pl? member=piapiac
  • 4. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 Reasons to store XML/JSON ● Client application uses it – Configuration – Serialised objects ● Data format/schema is highly complex/variable ● You just don't “care” about the data! – Audit data – Application log files
  • 5. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 Primer: XML ● eXtensible Markup Language ● Human readable data interchange & serialisation format ● Consists of a root element containing a mix of child elements and text content with any element having optional attributes <root> <child attribute=”value”> text based content </child> </root>
  • 6. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML Support ● ANSI and ISO standards exist – Introduced in SQL/XML 2003 – Augmented in SQL/XML 2006 ● Prior to 8.3 XML support was a contrib module ● Added to core in 8.3 but remains a compile time option enabled with: configure --with-libxml
  • 7. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML Support ● xml datatype (internally stored as text) ● Keywords from the standards – DOCUMENT, CONTENT – XMLPARSE, XMLSERIALIZE ... ● Predicates, also from the standards – IS [NOT] DOCUMENT – XMLEXISTS (9.1) ● A number of support functions, not standard – xmlconcat(), xpath() ...
  • 8. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: The Hard Way ● Using “standard” SQL, XML is inserted: INSERT INTO demo (data) VALUES (XMLPARSE (DOCUMENT '<? xml version="1.0"?> <book> <title>Manual</title> <chapter>...</chapter> </book>')) ● To retrieve using “standard” SQL: SELECT XMLSERIALIZE(DOCUMENT data AS text) FROM ...
  • 9. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: The Easy Way ● It's a normal datatype, use normal casting! ● INSERT (::xml is optional as text will implicitly cast to xml even in 9.3) pgday=# INSERT INTO demo (data) VALUES ('<?xml version="1.0"?> pgday-# <book> <title>Manual</title> pgday-# <chapter>...</chapter> </book>'::xml); INSERT 0 1
  • 10. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: The Easy Way ● SELECT (::text is optional as far as rendering in the psql client is concerned) pgday=# SELECT data::text FROM demo WHERE ... data ---------------------------------------------------------- <book><title>Manual</title><chapter>...</chapter></book> (1 row)
  • 11. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: xmloption ● When casting without XMLPARSE or XMLSERIALIZE the choice of DOCUMENT or CONTENT is determined by the value of the 'XML option' session variable SET XML OPTION { DOCUMENT | CONTENT} SET xmloption TO { DOCUMENT | CONTENT}
  • 12. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: Predicates ● IS DOCUMENT / IS NOT DOCUMENT – Use to filter between DOCUMENT and CONTENT – Only works with data that is already cast as XML pgday=# SELECT XMLSERIALIZE(DOCUMENT data AS text) FROM pgday-# WHERE data IS DOCUMENT; pgday=# SELECT XMLSERIALIZE(CONTENT data AS text) FROM pgday-# WHERE data IS NOT DOCUMENT;
  • 13. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: Predicates ● xml_is_well_formed() – Introduced in 9.1 and takes text as a parameter – Sensitive to XMLOPTION ● SET xmloption DOCUMENT; – Also xml_is_well_formed_documet() and xml_is_well_formed_content()
  • 14. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: xpath() xpath(xpath, xml [, nsarray]) ● Allows you to extract elements and text ● Supports namespaces ● Returns an array of XML ● Also returns empty arrays when there is no match SELECT xpath('//title/text()',data) FROM ...
  • 15. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: XMLEXISTS XMLEXISTS(text PASSING [BY REF] xml [BY REF]) ● From the standard, useful for predicates ● First parameter is an xpath expression SELECT xpath('//title/text()',data) FROM demo WHERE XMLEXISTS('//title' PASSING data);
  • 16. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 XML: xpath_exists() xpath_exists(xpath, xml [, nsarray]) ● Serves the same purpose as XMLEXISTS but: – Supports namespaces – Syntax is simplier SELECT xpath('//title/text()',data) FROM demo WHERE xpath_exists('//title', data);
  • 17. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 Primer: JSON ● JavaScript Object Notation ● Also a human readable data interchange & serialisation format ● { } denote objects containing a comma separated list of name value pairs where values can be nested objects or arrays { “name”:”value”, “nestedObject”: { “array”:[“value1”,”value2”] }, “numeric”:13 }
  • 18. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 JSON Support ● Not a SQL standard ● PostgreSQL is currently the only RDBMS with native support ● Design borrows heavily from PostgreSQL's existing XML support – Internal storage format is TEXT – Basic validation (e.g. well formed) ● Does not require special libraries to enable
  • 19. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 JSON Support ● Basic support introduced in 9.2 – JSON datatype – 2 support functions ● row_to_json() ● array_to_json() ● Operators and additional functions in 9.3 – ->,->>,#>,#>> – 10 more support functions
  • 20. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 JSON Support ● INSERT always ensures type validity pgday=# INSERT INTO demo VALUES pgday-# ('{"name":"Mike","hungry":true}'); INSERT 0 1 pgday=# INSERT INTO demo VALUES pgday-# ('{"name":"Mike",hungry:true}'); ERROR: invalid input syntax for type json at character 28
  • 21. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 JSON: Operators ● Retrieve the value of an attribute SELECT data->'name' AS name FROM … ● Use the value of an attribute in a predicate SELECT data FROM demo WHERE data->>'name' = 'Mike';
  • 22. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 JSON: Functions row_to_json(record [, pretty_bool]) Returns a result set where each row is a JSON object pgday=# SELECT * FROM demo; username | posts | email ----------+-------+------------------- mlfowler | 121 | mike@mlfowler.com fowlerm | 9 | mike@work.com pgday=# SELECT row_to_json(demo) FROM demo; row_to_json ----------------------------------------------------------------- {"username":"mlfowler","posts":121,"email":"mike@mlfowler.com"} {"username":"fowlerm","posts":9,"email":"mike@work.com"}
  • 23. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 JSON: Functions json_object_keys(json) Returns all the keys in the top level pgday=# SELECT json_object_keys(data) FROM demo; json_object_keys ------------------ name hungry
  • 24. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 Caveats ● They are not indexable – You will need to plan how best to retrieve ● Best used programmaticly – Syntax of XML and JSON can be unwieldy ● Non-UTF8 encoded databases ● Not portable
  • 25. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 Summary ● Using the PostgreSQL XML and JSON datatypes allows you finer control of an otherwise free format field ● PostgreSQL's XML non-standard support is much easier to use than the standard ● JSON is still being very actively developed
  • 26. Handling XML and JSON in the Database Mike Fowler, mike@mlfowler.com PGDayUK 2013 Thank you! Mike Fowler mike@mlfowler.com