Smart Systems for Home

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

PostgreSQL Error 22037: Non-Unique Keys in a JSON Object

· 8 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 22037 (sqlstate 22037, message "non-unique keys in a json object") means you asked PostgreSQL to turn a JSON object into a stricter jsonb value or otherwise validate it as an object, and that object contains a key that appears more than once. PostgreSQL's json type stores text verbatim and tolerates duplicate keys, but jsonb stores a parsed binary form where object keys must be unique, so the conversion fails. The fix is to find the duplicate key, decide which value should survive, and remove or rename the offending key before you cast. This walkthrough covers how to locate the duplicate, how to clean it, and how to prevent the error from returning.

What You'll Need

  • Access to a PostgreSQL database with a user that can read the affected table (and write if you plan to fix the data).
  • A client: psql on the command line, or any SQL client you already use, such as pgAdmin or DBeaver.
  • Knowledge of the column, table, and query that triggers the error, or a way to reproduce it.
  • A backup or a tested restore path before you change stored data.
  • An understanding of which key value is correct when a duplicate appears, because the database will not choose for you.

Step-by-Step

  1. Confirm the actual statement that failed. Reproduce the error in a query window and read the full message, not just the code. The 22037 code almost always comes from a cast like some_column::jsonb, a function that expects jsonb, or an insert into a jsonb column from text built by json_build_object or string concatenation. If the message names a function or shows the query, note exactly which expression is converting the value. This tells you whether the problem is one row, a generated expression, or application code building the JSON.
  2. Isolate the bad row. If the table stores JSON as text or as json, test the cast row by row and let the test catch the failure. A pattern like SELECT id FROM your_table WHERE NOT your_column::json IS NULL; will stop on the first invalid row in some clients, so instead wrap the cast in a PL/pgSQL block with an exception handler that logs the failing primary key and continues. A simple loop over the table, casting each value inside a BEGIN ... EXCEPTION WHEN others THEN RAISE NOTICE '%', id; END; block, produces the list of offending rows without aborting. For a single row, cast it directly and confirm the error reproduces.
  3. Look at the raw text of one bad value. Select the column as text, not as JSON, so PostgreSQL prints it exactly as stored. Scan for a key that appears twice, such as {"status":"open","status":"closed"}. Duplicates can be side by side or far apart, and they can be nested inside a sub-object or inside an object in an array. Nested duplicates raise the same error because jsonb requires unique keys at every level of an object, not just at the top.
  4. Find the source of the duplicate. Common causes are string concatenation that appends a key twice, json_build_object called with the same key name from two branches, a merge or update routine that adds a field without checking for it, and application code that serializes a map with a repeated field. Grep your application and stored procedures for the key name. Fixing the producer is more durable than cleaning individual rows, and it stops new duplicates from appearing after you repair the table.
  5. Decide which value wins. You need a rule: keep the last occurrence (typical for last-write-wins updates), keep the first occurrence, or keep a value chosen by some business rule such as the most recent timestamp. Write the rule down and apply it consistently, because different rows may have different orders. If the two values conflict and neither is clearly correct, flag the row for human review rather than guessing.
  6. Clean the value before casting. The safest route is to parse the text, remove the duplicate, and rebuild the object. For a top-level duplicate you can use jsonb itself after a workaround: no built-in function strips duplicate JSON keys silently, so the practical approach is to fix the text with a targeted update, or to build the corrected object from the individual fields with jsonb_set or by constructing a new object. For nested duplicates the same idea applies at the path where the key repeats. Test the expression on a copy of a few rows first with a SELECT, confirming it produces valid JSON, before you run the UPDATE.
  7. Migrate the column in a controlled order. If you are converting a whole table from json to jsonb, add a new jsonb column, fill it from the cleaned source in batches, check for leftover failures, then swap the columns in a maintenance window and rename the old one. Casting in place with ALTER TABLE ... ALTER COLUMN ... TYPE jsonb USING ... rewrites the table and fails entirely if any single row is bad, which is a painful way to discover a duplicate. Batches let you find and fix rows incrementally, and they keep locks short.
  8. Deploy the fix to the producer. Update the application or SQL routine that builds the JSON so it cannot emit a duplicate key. Many languages serialize a map or dictionary that silently collapses repeated fields, so check that the object is assembled from a single set of keys. Add a test that posts the payload with a duplicate key and asserts a clear validation error rather than a database crash.
  9. Add a guard. Validate incoming JSON at the boundary, for example by casting to jsonb inside a validation step and returning a friendly 400-level error, or by using a schema validator in the application before insert. Where the column is already jsonb, PostgreSQL guarantees uniqueness at every level after insert, so the guard is only needed on the text path.

Common Mistakes

  • Assuming json and jsonb behave the same. The json type accepts duplicate keys and keeps them; only the conversion, or a jsonb column, rejects them. People often blame the insert when the cast in a later query is the real culprit.
  • Only checking the top level. Duplicate keys anywhere in the object, including inside arrays of objects, trigger the error. Search the whole document.
  • Running the type change on the live table first. A failed ALTER TABLE ... TYPE jsonb shows the first error and aborts the whole rewrite, leaving you with no clean list of bad rows. Test in batches or on a clone.
  • Picking a value by habit. Silently keeping the last duplicate may discard the value that was actually meant. Establish the rule before the update.
  • Forgetting the application. Repairing rows without fixing the code means the duplicates return as soon as the next write happens.

Tips

  • Use jsonb_typeof to confirm a value is an object before you try to merge into it; functions like jsonb_set behave differently on scalars and arrays.
  • Prefer jsonb_build_object and jsonb_set over assembling JSON by pasting strings. Structured construction makes duplicate keys far less likely.
  • Keep a sample of the failing payload in your test suite so the bug cannot quietly come back.
  • When you audit a table, log the primary key of each failing row to a small audit table so you can fix values in controlled batches and resume after a restart.
  • Remember that column type changes rewrite the table and take a lock; run them in a quiet window and watch disk space.

Troubleshooting

The error still appears after cleaning the obvious row. More than one row is probably affected. Run the isolation loop again and compare the list to the rows you fixed. It is common to find the same malformed pattern across a batch of records created by one broken export or migration.

The error points to a function call, not a column. Some function requires jsonb and is casting its argument internally. Trace back to the value you passed in; if it comes from a parameter or a computed expression, log the raw text before the call.

The cast succeeds in a test query but fails in the application. The application may be sending a different payload, or it may be building the JSON twice and concatenating the results. Log the exact string at the point where it is used, then compare it character by character to the one that worked.

The table is huge and the batch update is slow. Process rows in chunks by primary key range, commit after each chunk, and use a WHERE clause that limits the scan to rows still needing repair. Rerun the isolation loop to confirm progress.

You cannot change the stored data. If the source system owns the records, fix the cast in your query instead: select the fields you need individually rather than casting the whole document, or accept the text form and parse it in the application, then raise the duplicate key problem with whoever produces the payload.

Frequently Asked Questions

Why does PostgreSQL allow duplicate keys in the json type at all?

The json type stores the input text unchanged, so it has no reason to reject duplicates. jsonb parses and normalizes the value into a binary structure where keys must be unique, which is why the check appears on conversion or on insert into a jsonb column.

What is the difference between error 22037 and 22032?

22037 is specifically about duplicate keys in an object. 22032 (invalid_json_text) covers malformed JSON that cannot be parsed at all, such as a missing brace or quote. Read the message text to distinguish them, since the fixes are different.

Does jsonb discard duplicate keys automatically?

No. The cast fails with 22037 rather than silently keeping one value. You must remove or rename the duplicate before the conversion succeeds, or the insert into a jsonb column will error.

Does this error also apply to JSON arrays?

Only to objects inside them. Arrays may contain repeated values, but any object element with a repeated key triggers 22037 when converted to jsonb.

Can a duplicate key come from json_build_object?

Yes. If you pass the same key name in two positions, such as json_build_object('a', 1, 'a', 2), the result contains the key twice. Use a single key per field and merge conditions in application logic instead.

Will fixing the rows stop the error permanently?

Only if the code that produced them is also fixed. Cleaning the table removes the current failures, but a broken insert or export will recreate the problem on the next write.