TigerData logo
TigerData logo
  • Product

    Tiger Cloud

    Robust elastic cloud platform for startups and enterprises

    Agentic Postgres

    Postgres for Agents

    TimescaleDB

    Postgres for time-series, real-time analytics and events

  • Docs
  • Pricing

    Pricing

    Enterprise Tier

  • Developer Hub

    Changelog

    Benchmarks

    Blog

    Community

    Customer Stories

    Events

    Support

    Integrations

    Launch Hub

  • Company

    Contact us

    About

    Timescale

    Partners

    Security

    Careers

Log InTry for free
Home
AWS Time-Series Database: Understanding Your OptionsStationary Time-Series AnalysisThe Best Time-Series Databases ComparedTime-Series Analysis and Forecasting With Python Alternatives to TimescaleWhat Are Open-Source Time-Series Databases—Understanding Your OptionsWhy Consider Using PostgreSQL for Time-Series Data?Time-Series Analysis in RWhat Is Temporal Data?What Is a Time Series and How Is It Used?Is Your Data Time Series? Data Types Supported by PostgreSQL and TimescaleUnderstanding Database Workloads: Variable, Bursty, and Uniform PatternsHow to Work With Time Series in Python?Tools for Working With Time-Series Analysis in PythonGuide to Time-Series Analysis in PythonUnderstanding Autoregressive Time-Series ModelingCreating a Fast Time-Series Graph With Postgres Materialized Views
Understanding PostgreSQLOptimizing Your Database: A Deep Dive into PostgreSQL Data TypesUnderstanding FROM in PostgreSQL (With Examples)How to Address ‘Error: Could Not Resize Shared Memory Segment’ How to Install PostgreSQL on MacOSUnderstanding FILTER in PostgreSQL (With Examples)Understanding GROUP BY in PostgreSQL (With Examples)PostgreSQL Join Type TheoryA Guide to PostgreSQL ViewsStructured vs. Semi-Structured vs. Unstructured Data in PostgreSQLUnderstanding Foreign Keys in PostgreSQLUnderstanding PostgreSQL User-Defined FunctionsUnderstanding PostgreSQL's COALESCE FunctionUnderstanding SQL Aggregate FunctionsUsing PostgreSQL UPDATE With JOINHow to Install PostgreSQL on Linux5 Common Connection Errors in PostgreSQL and How to Solve ThemUnderstanding HAVING in PostgreSQL (With Examples)How to Fix No Partition of Relation Found for Row in Postgres DatabasesHow to Fix Transaction ID Wraparound ExhaustionUnderstanding LIMIT in PostgreSQL (With Examples)Understanding PostgreSQL FunctionsUnderstanding ORDER BY in PostgreSQL (With Examples)Understanding WINDOW in PostgreSQL (With Examples)Understanding PostgreSQL WITHIN GROUPPostgreSQL Mathematical Functions: Enhancing Coding EfficiencyUnderstanding DISTINCT in PostgreSQL (With Examples)Using PostgreSQL String Functions for Improved Data AnalysisData Processing With PostgreSQL Window FunctionsPostgreSQL Joins : A SummaryUnderstanding OFFSET in PostgreSQL (With Examples)Understanding PostgreSQL Date and Time FunctionsWhat Is Data Compression and How Does It Work?What Is Data Transformation, and Why Is It Important?Understanding the Postgres string_agg FunctionWhat Is a PostgreSQL Left Join? And a Right Join?Understanding PostgreSQL SELECTSelf-Hosted or Cloud Database? A Countryside Reflection on Infrastructure ChoicesUnderstanding ACID Compliance Understanding percentile_cont() and percentile_disc() in PostgreSQLUnderstanding PostgreSQL Conditional FunctionsUnderstanding PostgreSQL Array FunctionsWhat Characters Are Allowed in PostgreSQL Strings?Understanding WHERE in PostgreSQL (With Examples)What Is a PostgreSQL Full Outer Join?What Is a PostgreSQL Cross Join?What Is a PostgreSQL Inner Join?Data Partitioning: What It Is and Why It MattersStrategies for Improving Postgres JOIN PerformanceUnderstanding the Postgres extract() FunctionUnderstanding the rank() and dense_rank() Functions in PostgreSQL
Guide to PostgreSQL PerformanceHow to Reduce Bloat in Large PostgreSQL TablesDesigning Your Database Schema: Wide vs. Narrow Postgres TablesBest Practices for Time-Series Data Modeling: Single or Multiple Partitioned Table(s) a.k.a. Hypertables Best Practices for (Time-)Series Metadata Tables A Guide to Data Analysis on PostgreSQLA Guide to Scaling PostgreSQLGuide to PostgreSQL SecurityHandling Large Objects in PostgresHow to Query JSON Metadata in PostgreSQLHow to Query JSONB in PostgreSQLHow to Use PostgreSQL for Data TransformationOptimizing Array Queries With GIN Indexes in PostgreSQLPg_partman vs. Hypertables for Postgres PartitioningPostgreSQL Performance Tuning: Designing and Implementing Your Database SchemaPostgreSQL Performance Tuning: Key ParametersPostgreSQL Performance Tuning: Optimizing Database IndexesDetermining the Optimal Postgres Partition SizeNavigating Growing PostgreSQL Tables With Partitioning (and More)Top PostgreSQL Drivers for PythonWhen to Consider Postgres PartitioningGuide to PostgreSQL Database OperationsUnderstanding PostgreSQL TablespacesWhat Is Audit Logging and How to Enable It in PostgreSQLGuide to Postgres Data ManagementHow to Index JSONB Columns in PostgreSQLHow to Monitor and Optimize PostgreSQL Index PerformanceSQL/JSON Data Model and JSON in SQL: A PostgreSQL PerspectiveA Guide to pg_restore (and pg_restore Example)PostgreSQL Performance Tuning: How to Size Your DatabaseAn Intro to Data Modeling on PostgreSQLExplaining PostgreSQL EXPLAINWhat Is a PostgreSQL Temporary View?A PostgreSQL Database Replication GuideHow to Compute Standard Deviation With PostgreSQLHow PostgreSQL Data Aggregation WorksBuilding a Scalable DatabaseRecursive Query in SQL: What It Is, and How to Write OneGuide to PostgreSQL Database DesignHow to Use Psycopg2: The PostgreSQL Adapter for Python
Best Practices for Scaling PostgreSQLHow to Design Your PostgreSQL Database: Two Schema ExamplesHow to Handle High-Cardinality Data in PostgreSQLHow to Store Video in PostgreSQL Using BYTEABest Practices for PostgreSQL Database OperationsHow to Manage Your Data With Data Retention PoliciesBest Practices for PostgreSQL AggregationBest Practices for Postgres Database ReplicationHow to Use a Common Table Expression (CTE) in SQLBest Practices for Postgres Data ManagementBest Practices for Postgres PerformanceBest Practices for Postgres SecurityBest Practices for PostgreSQL Data AnalysisTesting Postgres Ingest: INSERT vs. Batch INSERT vs. COPYHow to Use PostgreSQL for Data Normalization
PostgreSQL Extensions: amcheckPostgreSQL Extensions: Unlocking Multidimensional Points With Cube PostgreSQL Extensions: hstorePostgreSQL Extensions: ltreePostgreSQL Extensions: Secure Your Time-Series Data With pgcryptoPostgreSQL Extensions: pg_prewarmPostgreSQL Extensions: pgRoutingPostgreSQL Extensions: pg_stat_statementsPostgreSQL Extensions: Install pg_trgm for Data MatchingPostgreSQL Extensions: Turning PostgreSQL Into a Vector Database With pgvectorPostgreSQL Extensions: Database Testing With pgTAPPostgreSQL Extensions: PL/pgSQLPostgreSQL Extensions: Using PostGIS and Timescale for Advanced Geospatial InsightsPostgreSQL Extensions: Intro to uuid-ossp
Columnar Databases vs. Row-Oriented Databases: Which to Choose?Data Analytics vs. Real-Time Analytics: How to Pick Your Database (and Why It Should Be PostgreSQL)How to Choose a Real-Time Analytics DatabaseUnderstanding OLTPOLAP Workloads on PostgreSQL: A GuideHow to Choose an OLAP DatabasePostgreSQL as a Real-Time Analytics DatabaseWhat Is the Best Database for Real-Time AnalyticsHow to Build an IoT Pipeline for Real-Time Analytics in PostgreSQL
When Should You Use Full-Text Search vs. Vector Search?HNSW vs. DiskANNA Brief History of AI: How Did We Get Here, and What's Next?A Beginner’s Guide to Vector EmbeddingsPostgreSQL as a Vector Database: A Pgvector TutorialUsing Pgvector With PythonHow to Choose a Vector DatabaseVector Databases Are the Wrong AbstractionUnderstanding DiskANNA Guide to Cosine SimilarityStreaming DiskANN: How We Made PostgreSQL as Fast as Pinecone for Vector DataImplementing Cosine Similarity in PythonVector Database Basics: HNSWVector Database Options for AWSVector Store vs. Vector Database: Understanding the ConnectionPgvector vs. Pinecone: Vector Database Performance and Cost ComparisonHow to Build LLM Applications With Pgvector Vector Store in LangChainHow to Implement RAG With Amazon Bedrock and LangChainRetrieval-Augmented Generation With Claude Sonnet 3.5 and PgvectorRAG Is More Than Just Vector SearchPostgreSQL Hybrid Search Using Pgvector and CohereImplementing Filtered Semantic Search Using Pgvector and JavaScriptRefining Vector Search Queries With Time Filters in Pgvector: A TutorialUnderstanding Semantic SearchWhat Is Vector Search? Vector Search vs Semantic SearchText-to-SQL: A Developer’s Zero-to-Hero GuideNearest Neighbor Indexes: What Are IVFFlat Indexes in Pgvector and How Do They WorkBuilding an AI Image Gallery With OpenAI CLIP, Claude Sonnet 3.5, and Pgvector
Understanding IoT (Internet of Things)A Beginner’s Guide to IIoT and Industry 4.0Storing IoT Data: 8 Reasons Why You Should Use PostgreSQLMoving Past Legacy Systems: Data Historian vs. Time-Series DatabaseWhy You Should Use PostgreSQL for Industrial IoT DataHow to Choose an IoT DatabaseHow to Simulate a Basic IoT Sensor Dataset on PostgreSQLFrom Ingest to Insights in Milliseconds: Everactive's Tech Transformation With TimescaleHow Ndustrial Is Providing Fast Real-Time Queries and Safely Storing Client Data With 97 % CompressionHow Hopthru Powers Real-Time Transit Analytics From a 1 TB Table Migrating a Low-Code IoT Platform Storing 20M Records/DayHow United Manufacturing Hub Is Introducing Open Source to ManufacturingBuilding IoT Pipelines for Faster Analytics With IoT CoreVisualizing IoT Data at Scale With Hopara and TimescaleDB
What Is ClickHouse and How Does It Compare to PostgreSQL and TimescaleDB for Time Series?Timescale vs. Amazon RDS PostgreSQL: Up to 350x Faster Queries, 44 % Faster Ingest, 95 % Storage Savings for Time-Series DataWhat We Learned From Benchmarking Amazon Aurora PostgreSQL ServerlessTimescaleDB vs. Amazon Timestream: 6,000x Higher Inserts, 5-175x Faster Queries, 150-220x CheaperHow to Store Time-Series Data in MongoDB and Why That’s a Bad IdeaPostgreSQL + TimescaleDB: 1,000x Faster Queries, 90 % Data Compression, and Much MoreEye or the Tiger: Benchmarking Cassandra vs. TimescaleDB for Time-Series Data
Alternatives to RDSWhy Is RDS so Expensive? Understanding RDS Pricing and CostsEstimating RDS CostsHow to Migrate From AWS RDS for PostgreSQL to TimescaleAmazon Aurora vs. RDS: Understanding the Difference
5 InfluxDB Alternatives for Your Time-Series Data8 Reasons to Choose Timescale as Your InfluxDB Alternative InfluxQL, Flux, and SQL: Which Query Language Is Best? (With Cheatsheet)What InfluxDB Got WrongTimescaleDB vs. InfluxDB: Purpose Built Differently for Time-Series Data
5 Ways to Monitor Your PostgreSQL DatabaseHow to Migrate Your Data to Timescale (3 Ways)Postgres TOAST vs. Timescale CompressionBuilding Python Apps With PostgreSQL: A Developer's GuideData Visualization in PostgreSQL With Apache SupersetMore Time-Series Data Analysis, Fewer Lines of Code: Meet HyperfunctionsIs Postgres Partitioning Really That Hard? An Introduction To HypertablesPostgreSQL Materialized Views and Where to Find ThemTimescale Tips: Testing Your Chunk Size
Postgres cheat sheet
HomeTime series basicsPostgres basicsPostgres guidesPostgres best practicesPostgres extensionsPostgres for real-time analytics
Sections

Performance

Guide to PostgreSQL Performance

Schema design

PostgreSQL Performance Tuning: Designing and Implementing Your Database Schema

Performance tuning

PostgreSQL Performance Tuning: Key ParametersPostgreSQL Performance Tuning: Optimizing Database IndexesHow to Reduce Bloat in Large PostgreSQL TablesPostgreSQL Performance Tuning: How to Size Your Database

Partitioning

Determining the Optimal Postgres Partition SizeNavigating Growing PostgreSQL Tables With Partitioning (and More)When to Consider Postgres PartitioningPg_partman vs. Hypertables for Postgres Partitioning

Database design and modeling

An Intro to Data Modeling on PostgreSQLDesigning Your Database Schema: Wide vs. Narrow Postgres TablesBest Practices for Time-Series Data Modeling: Single or Multiple Partitioned Table(s) a.k.a. Hypertables Best Practices for (Time-)Series Metadata Tables Guide to PostgreSQL Database Design

Database replication

A PostgreSQL Database Replication Guide

Data analysis

A Guide to Data Analysis on PostgreSQLHow to Compute Standard Deviation With PostgreSQL

Data transformation

How to Use PostgreSQL for Data Transformation

Data aggregation

How PostgreSQL Data Aggregation Works

Scaling postgres

A Guide to Scaling PostgreSQLBuilding a Scalable Database

Database security

Guide to PostgreSQL SecurityWhat Is Audit Logging and How to Enable It in PostgreSQL

Data management

Understanding PostgreSQL TablespacesGuide to Postgres Data ManagementHandling Large Objects in Postgres

Database operations

Guide to PostgreSQL Database Operations

JSON

How to Query JSON Metadata in PostgreSQLHow to Query JSONB in PostgreSQLHow to Index JSONB Columns in PostgreSQLSQL/JSON Data Model and JSON in SQL: A PostgreSQL Perspective

Query optimization

Explaining PostgreSQL EXPLAINWhat Is a PostgreSQL Temporary View?Optimizing Array Queries With GIN Indexes in PostgreSQLRecursive Query in SQL: What It Is, and How to Write One

Database tools and libraries

How to Use Psycopg2: The PostgreSQL Adapter for PythonTop PostgreSQL Drivers for Python

Database indexes

How to Monitor and Optimize PostgreSQL Index Performance

Database backups and restore

A Guide to pg_restore (and pg_restore Example)

Products

Time Series and Analytics AI and Vector Enterprise Plan Cloud Status Support Security Cloud Terms of Service

Learn

Documentation Blog Forum Tutorials Changelog Success Stories Time Series Database

Company

Contact Us Careers About Brand Community Code Of Conduct Events

Subscribe to the Tiger Data Newsletter

By submitting, you acknowledge Tiger Data's Privacy Policy

2025 (c) Timescale, Inc., d/b/a Tiger Data. All rights reserved.

Privacy preferences
LegalPrivacySitemap

Published at Jan 29, 2025

How to Query JSON Metadata in PostgreSQL

Try for free

Start supercharging your PostgreSQL today.

Written by Warda Bibi

PostgreSQL is a highly capable relational database management system known for its powerful features and performance. One of its standout capabilities is its ability to manage unstructured data efficiently. Unstructured data refers to information that doesn't fit neatly into fixed columns and data types. It can include complex structures with varying data types.

In this blog, we will explore the power of JSON in PostgreSQL and demonstrate how to store and query unstructured data efficiently in JSON. 

JSON (JavaScript Object Notation) 

JSON, short for JavaScript Object Notation, is a process of storing data in “key-value” pairs format. It is a lightweight, human-readable data interchange format that is easy for computers to parse and generate.

It is a flexible, schema-less format that handles hierarchical and dynamic data. It allows us to store an arbitrary number of properties with varying types, lengths, and structures without worrying about fitting into a fixed table format.

Data types in JSON

JSON is primarily built on two core data structures: objects and arrays. JSON supports the following data types:

  • Array : [15.2, 16.5, 15.8]

  • Object: { "device_id": "device_789",  "timestamp": "2024-12-29T10:30:00Z", "battery": 85.4}

  • Number: 100, 9.99, etc.

  • Boolean: true or false

  • String: “Joe”

  • Null: null

Key point about JSON arrays

A JSON array is an ordered collection of values enclosed in square brackets [ ]. The significant feature of JSON arrays is their ability to hold heterogeneous (mixed) data types within the same array. This means that elements in a JSON array can vary in type. They can be a mix of numbers, strings, booleans, null, objects, or even other arrays.

For example, a JSON array can look like this:

[1, "hello", true, null, {"key": "value"}, [2, 3]]

JSON structure

A JSON might include an arbitrary set of properties, such as:

{   "device_id": "device_789",   "status": "active",   "battery": 85.4,   "location": {"city": "New York", "zip": "10001"},   "alerts": ["low_battery", "maintenance_due"],   "metadata": {"model": "device_X", "os_version": "v3.4"} }

This is a typical JSON object with key-value pairs for properties like status, battery, location, and alerts. Each property can hold different data types, such as strings, numbers, booleans, arrays, or nested objects. 

PostgreSQL Support for JSON

Postgres has native support for JSON starting from version 9.2 and onward releases. PostgreSQL provides two data types for working with JSON data: 

  • JSON

  • JSONB

The difference between JSON and JSONB is that JSON stores data in raw text form exactly as provided, while JSONB converts it to a binary format before storing it. As a result, writing to JSON is faster, but querying is slower, whereas writing to JSONB is slower, but querying is much faster.

Learn how to query JSONB in PostgreSQL.

Creating a JSON Column

Let's create a table for storing weather station data, where each row represents a single station. The table will include an ID column (as a primary key) and a JSON column to store the station data.

CREATE TABLE weather_stations (     id SERIAL PRIMARY KEY,     station_data JSON );

Let’s insert a record:

INSERT INTO weather_stations (station_data) VALUES (     '{         "station_name": "Weather Station Alpha",         "status": "active",         "location": {               "gps_coordinates": { "latitude": 37.7749, "Longitude":-122.4194   },                "nearby_cities": ["City A", "City B", "City C"],               "climatic_zones": ["Temperate", "Coastal"]          }     }'::json );

Note: The ::json casts the string into JSON format for storage.

 id |                            station_data                             ----+--------------------------------------------------------------------   1 | {                                                                 +     |         "station_name": "Weather Station Alpha",                  +     |         "status": "active",                                       +     |         "location": {                                             +     |               "gps_coordinates": {                                +     |                 "latitude": 37.7749,                             +     |                  "Longitude":-122.4194                            +     |                },                                                 +     |               "nearby_cities": ["City A", "City B", "City C"],    +     |               "climatic_zones": ["Temperate", "Coastal"]          +     |          }                                                        +     | }

Querying a JSON Column

PostgreSQL has two native operators for retrieving a JSON column:

  • Arrow operator  (->) -  returns a JSON object field

  • Arrow-text operator (->>) - returns the JSON object field as plain text

The arrow operator -> is suitable for navigating nested structures. 

Using the arrow-text operator, we can not query deeper into the structure because it’s no longer treated as an object. 

Retrieving a Specific JSON Key

Let's try to understand ->, ->> operators better with the help of a simple example. 

SELECT  station_data-> 'status' As Arrow, station_data->> 'status' As Arrow_text FROM weather_stations;

The output of the above query is:

  arrow   | arrow_text  ----------+------------  "active" | active

Here, status is a string so:

  • -> ’status’  should return an object field “active.” 

  • ->> ’status’ should return it as plain text active (without quotations if the value is a string).

Similarly, if we want to query the field ‘gps_coordinates’, we can use both -> and ->> operators. The results will appear the same, but internally, -> returns the entire object, whereas ->> extracts it as plain text.

SELECT  station_data-> 'location'-> 'gps_coordinates'  As Arrow, station_data-> 'location'->> 'gps_coordinates' As Arrow_text FROM weather_stations;

This query will return the gps_coordinates object for -> and the corresponding plain text value for ->>.

         arrow         |      arrow_text        -----------------------+-----------------------  {                    +| {                    +  "latitude": 37.7749, +| "latitude": 37.7749, +  "Longitude":-122.4194+| "Longitude":-122.4194+  }                     | } This means we cannot query deeper into ->> gps_coordinates because it returns a plain text value. 

Retrieving a Nested JSON Key

Let’s try to query deeper inside ‘location’ using -> and ->>.

SELECT  station_data->'location'->'nearby_cities' AS Arrow FROM weather_stations;

Output:

             arrow               --------------------------------  ["City A", "City B", "City C"]

This will work correctly because -> retains the JSON object format, allowing further traversal. However, the query:

SELECT  station_data->>'location'->>'nearby_cities' AS Arrow_text  FROM weather_stations; Error:

ERROR:  operator does not exist: text ->> unknown LINE 1: SELECT  station_data->>'location'->>'nearby_cities' AS Arrow...

                                         ^ HINT:  No operator matches the given name and argument types. You might need to add explicit type casts. This query results in an error because ->> extracts location as plain text and PostgreSQL cannot navigate further into plain text to access nearby_cities.

Filtering Rows Based on a Specific JSON Key Value

We can also use the -> and ->> operators in the WHERE clause. Let’s say we want to find all the active stations we can query.

SELECT * FROM weather_stations WHERE station_data->> 'status'='active' ; This query will return all rows where the status key in the station_data JSON column has the value 'active’.  id |                            station_data                             ----+--------------------------------------------------------------------   1 | {                                                                 +     |         "station_name": "Weather Station Alpha",                  +     |         "status": "active",                                       +     |         "location": {                                             +     |               "gps_coordinates": {                                +     |                   "latitude": 37.7749,                            +     |                   "Longitude":-122.4194                           +     |                },                                                 +     |               "nearby_cities": ["City A", "City B", "City C"],    +     |               "climatic_zones": ["Temperate", "Coastal"]          +     |         }                                                         +     | }

Querying arrays inside a JSON column

Let’s understand querying arrays inside a JSON column. Similar to querying any other key, we can access an array using the arrow operator (->). To query a specific position within an array, we use the arrow operator followed by the index of the desired element. If we want the result as plain text (e.g., retrieving the nearby_city as a string), we can use the ->> operator instead.

For example, to find the third nearby city for a station with id = 1, we can write:

SELECT station_data->'location'->'nearby_cities'->2  AS third_nearby_city FROM weather_stations WHERE id = 1;

Output:

 third_nearby_city  -------------------  "City C"

Note: Array indexing in PostgreSQL starts at 0, so the third city corresponds to index 2.

#> (Path Operator)

The #> operator is used to access elements in a JSON structure using a path. The path is specified as an array of keys and indices, allowing you to drill down into nested JSON objects or arrays.

SELECT station_data#>'{location,climatic_zones,1}' AS climatic_zone FROM weather_stations WHERE id = 1; Here, the top-level key is ‘location,’ and within that, there's another key ‘climatic_zones’ containing the array ["Temperate," "Coastal"]  where the value at index 1 is Coastal. The path '{location,climatic_zones,1}' means the following:

  • Start at the top-level key ‘location,’ which is a nested object.

  • Move into the ‘climatic_zones’ array.

  • Finally, extract the value of the index ‘1’.

This will give us the value "Coastal" at the index level.

 climatic_zone  ---------------  "Coastal" We also have a #>> operator. The difference between #> and #>> is exactly like the difference between -> and ->>. While #> returns a JSON object or array at a specified path, #>> returns the value as plain text. Use #>> for a text result instead of a JSON structure.

JSON Functions

to_ json

to_json() is a built-in JSON function that accepts any valid SQL value and converts it into JSON format. It can handle arrays, objects, and scalar values. The reason for converting a scalar value to a JSON is to ensure data consistency, especially in systems that expect JSON as a standard format, such as APIs or NoSQL databases. 

Scalar conversion

Scalars ( text, numbers, booleans) are converted into JSON, as shown below.

SELECT     TO_JSON(510),     TO_JSON(13.52),     TO_JSON('Command Prompt'::text),     TO_JSON(True);

Output: to_json | to_json |     to_json      | to_json  ---------+---------+------------------+---------  510     | 13.52   | "Command Prompt" | true

To verify that to_json(value) returns a JSON value, we can use the PostgreSQL system catalog function pg_typeof() to check the data type of the result.

SELECT to_json(35), pg_typeof(to_json(35));

Output:

 to_json | pg_typeof  ---------+-----------  35      | json

Array conversion

to_json can convert PostgreSQL arrays (including multidimensional) into JSON arrays.

SELECT to_json(ARRAY[1, 2, 3]); Output:

 to_json  ---------  [1,2,3]

Composite types conversion

to_json can also convert composite type into a JSON object, as shown below.

SELECT to_json(ROW(1, 'sensor', true));

Output:

             to_json               ----------------------------------  {"f1":1,"f2":"sensor","f3":true}

ROW is a PostgreSQL construct that creates an anonymous composite type (a temporary record or row) with the specified values. 

f1, f2, and f3 are the default field names assigned to the values in an anonymous composite type. 

array_to_json

array_to_json converts PostgreSQL arrays into a JSON representation. It supports multidimensional arrays, producing nested JSON arrays:

SELECT array_to_json('{{1,5},{99,100}}'::int[]);

Here, {{1,5},{99,100}} is a 2D integer array consisting of two inner arrays: {1, 5} and {99, 100}.   array_to_json    ------------------  [[1,5],[99,100]]

This query converts each inner array into a JSON array.

  • The first inner array [1, 5] becomes a JSON array [1, 5].

  • The second inner array [99, 100] becomes a JSON array [99, 100].

The outer array [ ] contains these two nested JSON arrays, resulting in the final JSON output: [[1, 5], [99, 100]]

Difference between to_json and array_to_json

The difference between to_json and array_to_json in array conversion is that to_json can convert any PostgreSQL value (including arrays) into JSON. In contrast, array_to_json is specifically designed for converting PostgreSQL arrays into JSON arrays, and it includes an optional pretty_bool parameter for formatting the output.

json_build_array

json_build_array is a PostgreSQL function that constructs a JSON array from a list of arguments. It supports elements of mixed types ( numbers, strings, booleans, etc.). The output is a JSON type, which is stored as text.

SELECT json_build_array(1, 2, 'three', true, null); Output:

      json_build_array        -----------------------------  [1, 2, "three", true, null]

The output [1, 2, "three," true, null] is a JSON array that contains mixed elements: two integers (1, 2), a string ("three"), a boolean (true), and a null value (null). JSON arrays can hold multiple types of values in a specific order without requiring key-value pairs.

json_build_object

json_build_object is a PostgreSQL function that allows the creation of a JSON object by specifying alternating key-value pairs. Each key is associated with a value, and the function constructs a JSON object where the keys and values are stored as pairs. SELECT json_build_object('name', 'sesnsorA', 'temperature', ‘100’, 'active', true);

Output:

                      json_build_object                        --------------------------------------------------------------  {"name" : "sesnsorA", "temperature" : "100", "active" : true}

This query creates a JSON object with three key-value pairs:

  •  "name": "sensorA", 

  •  "temperature": "100", 

  •   "active": "true"

json_object

json_object is a PostgreSQL function that creates a JSON object from a set of key-value pairs. 

Function signature

json_object has two valid function signatures:

  • Two-array approach:      json_object(keys TEXT[], values TEXT[]) 

  • Single-array approach:     json_object(keys_values TEXT[]) 

Two-array approach

It takes two text arrays as input:

  • One array represents keys. 

  • The other array represents values. 

Each element in the first array becomes a key, and the corresponding element in the second array becomes its value.

Both arrays must have the same number of elements, as each key is paired with the corresponding value to construct the JSON object.

SELECT json_object(array['device_name', 'sensor_id', 'status', 'battery_level'],array['Sensor_1', '12345', 'active', '85']);

Output:                              json_object                                             ---------------------------------------------------------------------------  {"device_name" : "Sensor_1", "sensor_id" : "12345", "status" : "active",   "battery_level" : "85"}

This query creates a JSON object where:

  • "device_name" maps to "Sensor_1."

  • "sensor_id" maps to "12345."

  • "status" maps to "active." 

  • "battery_level" maps to "85."

Single-array approach

Alternatively, we can pass a single text array containing both keys and values. In this case, alternate elements in the array are treated as keys and values, respectively.

SELECT json_object(array['device_name', 'Temp_Sensor', 'sensor_id', '98765', 'status', 'inactive', 'battery_level', '60']);

Output:

json_object                                               ------------------------------------------------------------------------------  {"device_name" : "Temp_Sensor", "sensor_id" : "98765", "status" : "inactive", "battery_level" : "60"}

The array is processed in pairs, and each pair is mapped as key value in the resulting JSON object. The first element ('device_name') becomes the key, and the next element ('Temp_Sensor') becomes its value. This pattern continues for the remaining pairs.

json_serialize

The json_serialize() function in PostgreSQL 17 converts a JSON expression into text or binary format. This function is particularly useful when we need to control the output format of JSON data or prepare it for transmission or storage in specific formats.

Function signature

The json_serialize() function uses the following syntax.

json_serialize(    expression          -- Input JSON expression     [ FORMAT JSON [ ENCODING UTF8 ]]       -- Optional input format specification     [ RETURNING data_type                  -- Optional return type specification       [ FORMAT JSON [ ENCODING UTF8 ] ] ]    -- Optional output format specification ) → text | bytea

Parameters:

  • expression: Inputs JSON value or expression to serialize

  • FORMAT JSON: Explicitly specifies JSON format for input (optional)

  • ENCODING UTF8: Specifies UTF8 encoding for input/output (optional)

  • RETURNING data_type: Specifies the desired output type (optional, defaults to text)

Note: Bytea is a data type used to store binary strings, which are sequences of bytes. When bytea data is displayed, it is often shown in a hexadecimal format, prefixed with \x.

For example,

\x7b20226122203a2031207d20 

is the hexadecimal representation of the JSON string { "a" : 1 }.

Example usage

Serializing JSON to binary (bytea)

To convert a JSON object into a compact binary format:

SELECT json_serialize( '{"id": 1, "data": "test"}'     RETURNING bytea ); The result of executing this query on PostgreSQL 17+ will be as follows:

# |                   json_serialize -------------------------------------------------------- 1 | \x7b226964223a20312c202264617461223a202274657374227d

This representation is space-efficient and suitable for storage or transmission in systems that prefer binary data.

Serializing JSON to text

To serialize a JSON object and return it as plain text:

SELECT json_serialize('{"name": "Alice", "age": 30}');

The result of executing this query on PostgreSQL 17 will be as follows.

# |       json_serialize -------------------------------- 1 | {"name": "Alice", "age": 30}

Comparison with the json() function

While both json_serialize() and json() are used with JSON data, their purposes differ.

  • json() converts text or binary data into JSON values.

  • json_serialize() converts JSON values into text or binary format.

  • json() emphasizes input validation, such as ensuring unique keys.

  • json_serialize() focuses on controlling the output format.

Think of these functions as complementary tools for handling JSON data

json() for input conversion

SELECT json('{"name": "sensorA"}');  -- Converts text to JSON

This query converts a text string '{"name": "sensorA"}' representing JSON into an actual JSON object in PostgreSQL.The output will be the JSON object {"name": "sensorA"}, stored in JSON format, allowing it to be used in JSON-specific operations in PostgreSQL.

json_serialize() for output conversion

SELECT json_serialize('{"name": "sensorA"}'::json);  -- Converts JSON to text

This query converts a JSON object back into a text representation of the JSON. This means we can no longer apply JSON-specific operations on the resulting string, as it is now just a regular string in PostgreSQL.

Conclusion

In summary, JSON is a powerful tool for handling JSON data within your PostgreSQL database. It allows the user to easily store, search, and manipulate complex data structures, making it a valuable asset for many applications. With its flexibility and powerful features, JSON can significantly enhance the capabilities of the database.

TimescaleDB, an open-source extension that expands PostgreSQL with robust optimizations for time series, real-time analytics, events, and vector data, supports JSON and JSONB for semi-structured data. Also, check out this article to learn more about handling complex JSONB columns for real-time aggregation. 

And since Timescale is PostgreSQL under the hood, you can benefit from PostgreSQL 17’s enhanced JSON support in all our Timescale Cloud services. Create a Timescale account and try it for free for 30 days (no credit card required).

On this page

    Try for free

    Start supercharging your PostgreSQL today.