Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL json_to_record: How to Convert JSON to Rows

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

The json_to_record function in PostgreSQL transforms a single JSON object into a structured record (a row) with specific columns and data types. This allows you to treat JSON keys as table columns, enabling you to use standard SQL filters, joins, and aggregations on semi-structured data. To use it, you must provide the JSON object and a column definition list that matches the keys you wish to extract.

What You'll Need

  • A PostgreSQL database (version 9.4 or newer).
  • A table containing json or jsonb data, or a raw JSON string to test with.
  • Basic knowledge of SQL SELECT statements and data types (e.g., TEXT, INTEGER, BOOLEAN).

Step-by-Step

  1. Identify your JSON structure Before writing the query, examine the JSON object you want to convert. Note the exact keys and the types of values they hold. For example, if your JSON is {"id": 101, "name": "Widget", "active": true}, you have an integer, a string, and a boolean.
  2. Define the target schema The json_to_record function requires an AS clause. This clause defines the column names and data types that PostgreSQL should create for the resulting record. These names must match the keys in your JSON object exactly.

    Example schema: AS (id INT, name TEXT, active BOOLEAN)
  3. Implement the function in the FROM clause Unlike standard functions that return a single value, json_to_record returns a record. Therefore, it must be placed in the FROM clause of your query. This treats the function output as if it were a virtual table.

    Basic Syntax:
    SELECT * FROM json_to_record('{"id": 101, "name": "Widget", "active": true}') AS x(id INT, name TEXT, active BOOLEAN);
  4. Apply the function to a table column To convert JSON stored in a table, use a CROSS JOIN LATERAL. This allows the function to reference a column from the preceding table in the FROM clause for every row.

    Example:
    SELECT t.id, j.name, j.active FROM my_table t, json_to_record(t.json_column) AS j(name TEXT, active BOOLEAN);
  5. Filter and manipulate the resulting columns Now that the JSON is converted to a record, you can use a WHERE clause to filter based on the newly created columns, just as you would with a standard table.

    Example:
    SELECT j.name FROM my_table t, json_to_record(t.json_column) AS j(name TEXT, active BOOLEAN) WHERE j.active = true;

Common Mistakes

  • Mismatching Key Names: If the column name in the AS clause does not match the key in the JSON object exactly (including case sensitivity), PostgreSQL will return a NULL value for that column rather than throwing an error.
  • Incorrect Data Types: Providing a data type that is incompatible with the JSON value (e.g., trying to cast a string "Hello" to an INTEGER) will result in a runtime error.
  • Using it in the SELECT list: Attempting to use json_to_record directly in the SELECT list (e.g., SELECT json_to_record(...) FROM table) will fail because the function returns a record type, not a scalar value. It must be in the FROM clause.
  • Confusing it with json_populate_record: json_to_record allows you to define the columns on the fly. json_populate_record requires an existing table or composite type to define the structure.

Tips

  • Use jsonb_to_record for Performance: If your data is stored as jsonb (binary JSON), use jsonb_to_record instead. It is generally faster and more efficient for processing.
  • Combine with json_array_elements: If you have a JSON array of objects, use json_array_elements first to expand the array into individual rows, then use json_to_record to turn those objects into columns.
  • Alias your records: Always provide a clear alias (like AS j or AS data) for the record. This makes your SELECT list much more readable when joining multiple tables.

Troubleshooting

If your query is not returning the expected results, try these steps in order:

  1. Check for NULLs: If columns are coming back as NULL, verify the case sensitivity of your JSON keys. JSON keys are case-sensitive; "Name" is not the same as "name".
  2. Validate JSON Format: Ensure the input is a valid JSON object (surrounded by curly braces {}). If the input is a JSON array (surrounded by square brackets []), json_to_record will fail. Use json_array_elements first.
  3. Verify Data Types: If you receive a "type mismatch" error, check the values in your JSON. Ensure that numeric fields don't contain unexpected strings or empty quotes that cannot be cast to integers.
  4. Test with a Static String: Replace your table column with a hardcoded JSON string (e.g., '{"a": 1}') to determine if the issue lies with the function syntax or the data stored in your table.

Frequently Asked Questions

What is the difference between json_to_record and json_to_recordset?

json_to_record converts a single JSON object into one row. json_to_recordset converts a JSON array of objects into multiple rows.

Can I use this function with the JSONB data type?

Yes, but you should use the corresponding jsonb_to_record function for better performance and compatibility with jsonb columns.

Do I have to define every single key in the JSON object?

No. You only need to define the keys you actually want to extract. Any keys present in the JSON object that are not listed in the AS clause will be ignored.

Is json_to_record faster than using the ->> operator?

For extracting a single value, the ->> operator is faster. However, when extracting many fields from the same object, json_to_record is often more readable and can be more efficient as it parses the object once for all defined columns.

Can I use this function in a View?

Yes. You can create a standard SQL View that uses json_to_record in the FROM clause. This is a common way to present semi-structured JSON data as a traditional relational table to end-users or BI tools.