Smart Systems for Home

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

Fix PostgreSQL Error 22034: More Than One SQL JSON Item

· 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

PostgreSQL error code 22034, labeled more_than_one_sql_json_item, occurs when a function or operator expects a single JSON value but receives multiple items that cannot be resolved into one. This typically happens during JSON array processing, aggregation, or when using functions like jsonb_agg or json_array_elements incorrectly in contexts requiring scalar output. To fix it, you must ensure your query logic extracts exactly one element from the JSON structure or aggregates multiple elements correctly into a single JSON object or array.

What You'll Need

  • A PostgreSQL database instance (version 9.5 or later for full JSONB support).
  • Access to a SQL client (such as psql, pgAdmin, DBeaver, or DataGrip).
  • The specific query causing the error.
  • Understanding of the JSON data structure involved (object vs. array).

Step-by-Step

  1. Identify the offending function or operator. Look at the error message context. The error usually points to a specific line in your query where a JSON operation is performed. Common culprits include jsonb_populate_record, json_to_recordset, or direct casting operations like ::jsonb on ambiguous inputs.
  2. Analyze the input data structure. Check if the column or expression being processed contains a JSON array with multiple top-level objects when a single object was expected. For example, if you are trying to convert a JSON array [{"a":1}, {"b":2}] directly into a record without unnesting, PostgreSQL may throw this error if it expects a single item.
  3. Use jsonb_array_elements to flatten arrays. If your source data is an array and you need to process each item individually before aggregating or filtering, wrap the column in jsonb_array_elements(). This converts the array into a set of rows. Example: SELECT * FROM jsonb_array_elements(my_column::jsonb) AS elem;
  4. Aggregate results back into a single JSON item if necessary. If the downstream logic requires a single JSON value but you have multiple rows after unnesting, use jsonb_agg() or json_object_agg() to combine them back into a single JSON array or object. Example: SELECT jsonb_agg(elem) FROM jsonb_array_elements(my_column::jsonb) AS elem;
  5. Check for duplicate keys in object construction. When building JSON objects manually using json_build_object() or jsonb_build_object(), ensure you are not inadvertently creating structures that conflict with existing constraints or expectations in subsequent joins or casts. While this doesn't always trigger 22034 directly, malformed intermediate states can lead to resolution errors.
  6. Validate explicit type casting. Ensure you are casting to the correct type. Use ::jsonb instead of ::json for better performance and indexing capabilities. If you are selecting a specific path, use the arrow operators (-> for JSON, ->> for text) carefully. Selecting a non-existent key returns NULL, which might cause issues if the next step expects a concrete JSON item.
  7. Rewrite subqueries to return single values. If you are using a subquery inside a SELECT clause that returns multiple rows because the underlying JSON has multiple matching items, add a LIMIT 1 or aggregate the result. PostgreSQL requires scalar subqueries to return exactly one row.

Common Mistakes

One frequent mistake is assuming that accessing a JSON array via index notation (e.g., my_json->0) will automatically handle cases where the array is empty or missing. If the structure is inconsistent across rows, some rows may yield multiple candidates or none, leading to ambiguity in certain join conditions or aggregation contexts.

Another common error is mixing json and jsonb types without explicit casting. While they are compatible, implicit conversions can sometimes fail if the parser encounters unexpected whitespace or formatting differences that make it difficult to determine if the content represents one item or many.

Developers often forget to unnest arrays before applying filters. Filtering a JSON array column directly does not remove elements from the array; it only includes or excludes the entire row. To filter individual elements within the JSON, you must first expand the array into rows.

Tips

Use jsonb_pretty() to inspect complex JSON structures during debugging. This makes it easier to visually confirm whether your data is an object, an array, or a nested mix, helping you decide whether to use jsonb_array_elements or direct key access.

If you are working with large datasets, prefer jsonb over json. The binary format is faster to parse and supports GIN indexes, which can significantly speed up queries involving containment operators (@>) or existence checks (?>).

Always test your JSON manipulation logic with edge cases: empty arrays, null values, and deeply nested objects. These scenarios are most likely to produce ambiguous results that trigger error 22034.

Troubleshooting

If the error persists after adjusting your query:

  1. Isolate the problematic expression. Break down your query into smaller parts. Run just the JSON extraction part in a separate SELECT statement to see what it returns. If it returns multiple rows when you expect one, that is the source of the issue.
  2. Check for implicit cardinality changes. Review any JOINs involving the JSON column. A join condition that matches multiple JSON items against a single key can inflate the result set unexpectedly, causing downstream aggregations or scalar subqueries to fail.
  3. Verify data integrity. Ensure that the JSON stored in the database is valid. Corrupted JSON strings might parse partially or ambiguously. Use IS JSON predicates (available in newer versions) or try-catch blocks in procedural languages to validate input.
  4. Review PostgreSQL version specifics. Behavior around JSON handling has improved over time. If you are on an older version, consider upgrading, as some parsing ambiguities were resolved in later releases.

Frequently Asked Questions

Why does my query work in development but fail in production?

Data variability is the most likely cause. In development, your test data might consistently contain single-item arrays or simple objects. In production, real-world data often includes multi-item arrays or nested structures that violate the assumptions of your query logic, triggering the "more than one item" error.

Can I ignore this error by setting a configuration parameter?

No. There is no PostgreSQL configuration flag to suppress error 22034. It is a logical error indicating that the database cannot unambiguously resolve the requested data shape. You must modify the query to explicitly handle multiple items, either by limiting, aggregating, or unnesting.

Does this error apply to all JSON functions?

It primarily affects functions and operators that expect a scalar JSON value or a single record. Functions designed to handle sets, such as jsonb_array_elements, do not throw this error themselves but are often used to fix queries that previously did. Aggregation functions like jsonb_agg are safe for multiple items.

How do I extract the first item from a JSON array safely?

Use the index operator combined with a fallback. For example: COALESCE(my_column->0, '{}'::jsonb). This ensures that if the array is empty or the column is null, you get a default empty object rather than an error or null propagation that might break subsequent steps.