Smart Systems for Home

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

PostgreSQL json_each_text: How to Expand JSON Objects

· 4 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_each_text function in PostgreSQL expands a JSON object into a set of rows, where each row contains a key and a value, both returned as the text data type. This is primarily used to flatten JSON data so that you can filter, join, or aggregate individual attributes stored within a JSON column as if they were standard table rows.

What You'll Need

  • A PostgreSQL database (version 9.4 or newer).
  • A table containing a column with the json data type.
  • Basic knowledge of SQL SELECT statements and the LATERAL JOIN (or comma-join) syntax.

Step-by-Step

  1. Identify your JSON source: Ensure you have a table with a json column. If your column is jsonb, you should use the corresponding jsonb_each_text function instead, as it is optimized for binary storage.
  2. Basic function call: To test the function on a single piece of data, call it using a SELECT statement.
    SELECT * FROM json_each_text('{"name": "John", "city": "New York", "role": "Admin"}');
    This will return a table with two columns: key and value.
  3. Join the function to a table: To expand JSON data stored in a table, use the function in the FROM clause. Because the function depends on a value from the table, PostgreSQL treats this as a lateral join.
    SELECT users.id, kv.key, kv.value FROM users, json_each_text(users.metadata) AS kv;
    In this example, users.metadata is the JSON column, and kv is the alias for the resulting key-value pairs.
  4. Filter by key or value: Once the JSON is expanded into rows, you can use a standard WHERE clause to find specific data.
    SELECT users.id, kv.value FROM users, json_each_text(users.metadata) AS kv WHERE kv.key = 'role' AND kv.value = 'Admin';
  5. Aggregate the expanded data: You can use the expanded rows to perform counts or groupings. For example, to see how many users have a specific attribute:
    SELECT kv.key, count(*) FROM users, json_each_text(users.metadata) AS kv GROUP BY kv.key;

Common Mistakes

  • Using it on JSON Arrays: json_each_text only works on JSON objects (curly braces {}). If you try to use it on a JSON array (square brackets []), PostgreSQL will throw an error. For arrays, use json_array_elements_text.
  • Confusing json and jsonb: Using json_each_text on a jsonb column will cause an implicit type cast, which can slow down performance on large datasets. Always match the function to the data type: json_each_text for json and jsonb_each_text for jsonb.
  • Ignoring Nulls: If the JSON column is NULL, the function returns no rows for that record. If you want to keep the record in your results even if the JSON is empty or null, use a LEFT JOIN LATERAL instead of a comma-join.

Tips

  • Performance: If you frequently need to expand JSON to filter data, consider using jsonb with a GIN index. This allows you to query the JSON directly without needing to expand it into rows first.
  • Type Casting: Since json_each_text returns everything as text, you must explicitly cast the value if you need to perform math or date comparisons. For example: (kv.value)::integer.
  • Alias naming: Always provide a clear alias (like kv for key-value) for the function output to keep your SELECT and WHERE clauses readable.

Troubleshooting

If the function does not go to plan, check the following:

  • Error: "cannot extract elements from a scalar": This happens if the data in your column is not a JSON object (e.g., it is just a string or a number). Verify your data integrity using SELECT column FROM table WHERE json_typeof(column) != 'object';
  • Missing Rows: If some table rows are disappearing from your results, it is because the JSON column is empty or null. Change your join to: FROM users LEFT JOIN LATERAL json_each_text(users.metadata) AS kv ON true.
  • Unexpected Data Types: If you see quotes around your values, you might be using json_each instead of json_each_text. The _text version removes the JSON quotes and returns a plain PostgreSQL text string.

Frequently Asked Questions

What is the difference between json_each and json_each_text?

json_each returns the value as a json type, meaning strings will still have double quotes around them. json_each_text converts the value directly to a PostgreSQL text type, removing the JSON formatting.

Can I use this function in a WHERE clause?

Not directly. The function returns a set of rows (a table), so it must be used in the FROM clause or within a subquery/CTE to be filtered.

Does this function work with nested JSON objects?

It only expands the top level of the object. If a value is another JSON object, that object will be returned as a single text string. To expand nested objects, you would need to call the function again on the resulting value.

How do I handle JSON arrays instead of objects?

Use json_array_elements_text. While json_each_text looks for key-value pairs, json_array_elements_text simply lists every element in the array as a new row.

Is json_each_text slow on large tables?

Yes, because it must expand the JSON for every row during the scan. For high-performance filtering on large datasets, jsonb with GIN indexing is significantly faster than expanding the data at runtime.