PostgreSQL json_each_text: How to Expand JSON Objects
In this article
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
jsondata type. - Basic knowledge of SQL
SELECTstatements and theLATERAL JOIN(or comma-join) syntax.
Step-by-Step
- Identify your JSON source: Ensure you have a table with a
jsoncolumn. If your column isjsonb, you should use the correspondingjsonb_each_textfunction instead, as it is optimized for binary storage. - Basic function call: To test the function on a single piece of data, call it using a
SELECTstatement.SELECT * FROM json_each_text('{"name": "John", "city": "New York", "role": "Admin"}');
This will return a table with two columns:keyandvalue. - Join the function to a table: To expand JSON data stored in a table, use the function in the
FROMclause. 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.metadatais the JSON column, andkvis the alias for the resulting key-value pairs. - Filter by key or value: Once the JSON is expanded into rows, you can use a standard
WHEREclause 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'; - 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_textonly 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, usejson_array_elements_text. - Confusing json and jsonb: Using
json_each_texton ajsonbcolumn will cause an implicit type cast, which can slow down performance on large datasets. Always match the function to the data type:json_each_textforjsonandjsonb_each_textforjsonb. - 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 aLEFT JOIN LATERALinstead of a comma-join.
Tips
- Performance: If you frequently need to expand JSON to filter data, consider using
jsonbwith a GIN index. This allows you to query the JSON directly without needing to expand it into rows first. - Type Casting: Since
json_each_textreturns everything astext, 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
kvfor key-value) for the function output to keep yourSELECTandWHEREclauses 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_eachinstead ofjson_each_text. The_textversion 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.