5 Postgres and JSON
This chapter covers
- Storing JSON data in Postgres
- Querying JSON data using built-in operators and functions
- Updating specific fields in existing JSON objects
- Optimizing JSON data access with GIN and B-tree indexes
Postgres introduced initial support for JSON back in 2012. Since then, JSON-specific capabilities and improvements have been added on a regular basis. Today, Postgres offers mature and comprehensive JSON support so that it can easily function as a document database, storing and processing JSON objects of various complexity.
Let’s explore Postgres’s JSON capabilities as we build an application for a pizza chain with hundreds of locations nationwide. We’ll learn how to store customer order details in JSON format and then work with this data while fulfilling orders and analyzing customers’ pizza preferences.
5.1 Storing JSON data
Imagine that we are part of the team building the application for the pizza chain. When a customer places a pizza order via the mobile or web frontend, our application backend receives the order details in JSON format. A sample order looks as follows:
{
"size": "medium",
"type": "margherita",
"crust": "regular",
"sauce": "marinara",
"toppings": {
"cheese": [
{"mozzarella": "regular"}
],
"veggies": [
{"tomato": "light"}
]
}
}