PostgreSQL is an awesome database, with an awesome data type, JSON. It actually has two JSON data types, json and jsonb.
JSON data types are for storing JSON (JavaScript Object Notation) data.
There are two JSON data types: json and jsonb. They accept almost identical sets of values as input. The major practical difference is one of efficiency. The json data type stores an exact copy of the input text, which processing functions must reparse on each execution; while jsonb data is stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed. jsonb also supports indexing, which can be a significant advantage.
In this article we will focus on one function in particular:
jsonb_to_recordset(jsonb data).
This function is particularly useful when you have an Array of Objects and want to query against the Values of one or more Keys using standard comparison operators including wildcards.
For example, we may have jsonb data like this, showing products purchased by a customer.
[{
"productid": "3",
"name": "Virtual Keyboard",
"price": "150.00"
}, {
"productid": "1",
"name": "Dell 123 Laptop Computer",
"price": "1300.00"
},
{
"productid": "8",
"name": "LG Ultrawide Monitor",
"price": "190.00"
}
]
If we have several customers and their purchases stored in a jsonb column, we may want to know things like,
and many others, of course.
I will assume you have PostgreSQL and something along the lines of pgAdmin.
CREATE TABLE public.purchases
(
id serial PRIMARY KEY,
purchaser varchar(50),
items_purchased jsonb
);
4. Run the snippet below to insert four records in to the table.
INSERT INTO purchases (purchaser,items_purchased) VALUES ('Bob','[{
"productid": "1",
"name": "Dell 123 Laptop Computer",
"price": "1300.00"
},
{
"productid": "2",
"name": "Mechanical Keyboard",
"price": "120.00"
}
]');
INSERT INTO purchases (purchaser,items_purchased) VALUES ('Carol','[{
"productid": "3",
"name": "Virtual Keyboard",
"price": "150.00"
}, {
"productid": "1",
"name": "Dell 123 Laptop Computer",
"price": "1300.00"
},
{
"productid": "8",
"name": "LG Ultrawide Monitor",
"price": "190.00"
}
]');
INSERT INTO purchases (purchaser,items_purchased) VALUES ('Ted','[{
"productid": "6",
"name": "Ergonomic Keyboard",
"price": "90.00"
},
{
"productid": "7",
"name": "Dell 789 Desktop Computer",
"price": "120.00"
}
]');
INSERT INTO purchases (purchaser,items_purchased) VALUES ('Alice','[{
"productid": "7",
"name": "Dell 789 Desktop Computer",
"price": "120.00"
},
{
"productid": "2",
"name": "Mechanical Keyboard",
"price": "120.00"
}
]');
#api-development #postgresql #nosql #postgres #json