sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" >> /etc/apt/sources.list.d/pgdg.list'
wget -q https://www.postgresql.org/media/keys/ACCC4CF8.asc -O - | sudo apt-key add -
sudo apt-get update
sudo apt-get install postgresql postgresql-contrib postgresql-server-dev-9.5
You can declare a JSON column just like a column of any other data type.
CREATE TABLE sales (id INT, sale JSON);
Insertion of data is pretty close to that of any other data type as well, except that you have to make sure the data is in a valid JSON format.
INSERT INTO sales
VALUES (1,'{ "customer_name": "John",
"items": { "description": "milk", "quantity": 4 } }');
SELECT * FROM sales;
PostgreSQL provides native operators to retrieve individual nodes of the JSON object. The ‘->’ operator returns a JSON object and the ‘->>’ operator returns TEXT.
SELECT sale->'customer_name' AS name FROM sales;
SELECT sale->>'customer_name' AS name FROM sales;
‘->’ returns a JSON object, you can use it to return a nested object within the data and chain it with the operator ‘->>’ to retrieve a specific node.
SELECT id, sale->'items'->>'quantity' AS quantity FROM sales;
SELECT sale->'customer_name' AS name FROM sales;
The operators discussed in the previous section can be used in the WHERE clause of a query to specify an extract criteria.
Searching for a specific description of an item within a sale:
SELECT * FROM sales WHERE sale->'items'->>'description' = 'milk';
Searching for a specific quantity as TEXT:
SELECT * FROM sales WHERE sale->'items'->>'quantity' = 12::TEXT;
Searching for a specific quantity as INTEGER:
SELECT * FROM sales WHERE CAST(sale->'items'->>'quantity' AS integer) = 2;
SELECT SUM(CAST(sale->'items'->>'quantity' AS integer)) AS total_quantity_sold FROM sales;
PostgreSQL provides for manipulating JSON objects.
This function expands the outermost JSON object into a set of key/value pairs. Notice that the nested JSONs are not expanded.
SELECT json_each(sale) FROM sales;
Returns set of keys in the outermost JSON object. Again, notice that the nested keys are not displayed.
SELECT json_object_keys(sale) FROM sales;
Returns the type of the outermost JSON value as a text string. Possible types are ‘object’, ‘array’, ‘string’, ‘number’, ‘boolean’, and NULL.
SELECT json_typeof(sale->'items'), json_typeof(sale->'items'->'quantity') FROM sales;
Builds a JSON object out of a text array. The function can be used in one of two ways:
-
Array with exactly one dimension with an even number of members. In this case the elements are taken as alternating key/value pairs.
SELECT json_object('{key1, 6.4, key2, 9, key3, "value"}');
-
Array with two dimensions such that each inner array has exactly two elements. In this case, the inner array elements are taken as a key/value pair.
SELECT * FROM json_object('{{key1, 6.4}, {key2, 9}, {key3, "value"}}');
Returns the value as a JSON object.
CREATE TABLE json_test (id INT, name TEXT);