PostgreSQL Error 22030 Duplicate JSON Object Key Value
In this article
PostgreSQL error 22030 occurs when you attempt to insert or update a JSON or JSONB field with an object containing duplicate keys. PostgreSQL enforces strict JSON validity and rejects objects with repeated keys because they violate the JSON specification as interpreted by the database. This error is not a bug—it’s a safeguard. You must remove duplicate keys from your JSON data before insertion or update. This guide shows you how to identify, fix, and prevent this error in real-world scenarios.
What You'll Need
- A PostgreSQL database (version 9.4 or later, since JSONB was introduced)
- Access to the table containing the JSON or JSONB column
- A tool to inspect or edit JSON data (e.g., psql, pgAdmin, a text editor, or a JSON validator)
- Basic familiarity with SQL and JSON structure
Step-by-Step
- Identify the problematic JSON field by reviewing the error message. It will include the exact column name and often the duplicate key, such as
duplicate JSON object key: "name". - Retrieve the faulty row using a SELECT query. For example:
SELECT id, json_column FROM your_table WHERE id = 123;Replaceidandjson_columnwith your actual column names. - Copy the JSON value from the result and paste it into a JSON validator tool (like jsonlint.com or VS Code with JSON extension) to visually inspect the structure. Look for keys that appear more than once at the same nesting level.
- Modify the JSON to remove duplicate keys. Keep only the last occurrence if the values differ, or decide which value to retain. For example, change
{"name": "Alice", "age": 30, "name": "Bob"}to{"name": "Bob", "age": 30}. - If you’re updating the row via SQL, use the
jsonb_set()function or rebuild the object entirely. For example:UPDATE your_table SET json_column = '{"name": "Bob", "age": 30}'::jsonb WHERE id = 123;Always cast tojsonbto ensure validity. - Test the update with a dry run using a
SELECTstatement first:SELECT '{"name": "Bob", "age": 30}'::jsonb;Confirm it returns without error. - Run the
UPDATEcommand. If successful, the error will disappear. If not, re-check the JSON for hidden duplicates, such as nested objects with identical keys. - For bulk fixes, write a script in Python, Node.js, or psql to parse and clean all JSON values. Use a library like Python’s
jsonmodule to load and dump the data—this automatically removes duplicates during parsing.
Common Mistakes
- Assuming the last duplicate key should override the first. PostgreSQL does not allow this—it rejects the entire object, regardless of which key appears last.
- Using string concatenation to build JSON, which can accidentally create duplicates (e.g.,
SELECT '{"key": "val", "key": "val2"}'). - Believing that JSONB automatically resolves duplicates. It does not. JSONB strips duplicates during storage, but only if the object is valid when inserted. If the input is invalid (duplicate keys), PostgreSQL refuses the operation entirely.
- Editing JSON manually without validating the syntax. A missing comma or extra quote can mask the real issue.
- Trying to use
json_each()orjsonb_each()to fix duplicates without understanding they return key-value pairs and do not reconstruct the object.
Tips
- Always validate JSON before inserting it into PostgreSQL. Use a validator or a simple script to check structure.
- When generating JSON programmatically (e.g., from an API or application), ensure your serializer (like Python’s
json.dumps()) is not merging or duplicating keys from malformed input. - Use JSONB instead of JSON for storage—it’s more efficient and enforces stricter validation.
- Set up application-level logging to capture malformed JSON before it reaches the database. This prevents the error from occurring in production.
- For dynamic JSON objects, enforce unique keys in your code logic before serialization. For example, use a dictionary or object with key uniqueness checks.
- Test edge cases: empty objects, deeply nested structures, and arrays containing objects with repeated keys.
Troubleshooting
If the error persists after following the steps above, check these areas:
- Verify that the JSON string you’re inserting isn’t being altered by triggers, functions, or application middleware. Some systems automatically merge fields and may introduce duplicates.
- Check for invisible Unicode characters or whitespace around keys. Use
SELECT length(json_column::text), json_column FROM your_table;to compare lengths before and after editing. - If using a JSONB column, try casting the value to TEXT first:
SELECT json_column::text FROM your_table;Then manually inspect for duplicate keys in the raw text. - Try inserting a minimal valid JSON object (e.g.,
{"test": 1}) into the same column. If that works, the issue is definitely in your data, not the schema. - If you’re using a framework (like Django, Rails, or Node.js), review how it serializes model fields. Some ORMs may serialize nested objects incorrectly.
- If the data came from an external source (like a CSV or API), inspect the source for malformed entries. You may need to clean the data upstream.
Frequently Asked Questions
Can PostgreSQL automatically remove duplicate JSON keys?
No. PostgreSQL rejects the entire JSON object if it contains duplicate keys. It does not silently drop or overwrite them. You must fix the data before insertion.
Why does PostgreSQL treat duplicate keys as invalid when other systems accept them?
The JSON standard (RFC 7159) states that object keys should be unique. While some parsers tolerate duplicates, PostgreSQL follows strict validation to ensure data integrity and predictable behavior.
How do I find duplicate keys in a large JSON field without manual inspection?
Use a SQL query with jsonb_each() and GROUP BY to count occurrences. For example: SELECT key, COUNT(*) FROM jsonb_each(json_column) GROUP BY key HAVING COUNT(*) > 1; This returns all keys appearing more than once.
Can I use a trigger to automatically clean duplicate keys before insertion?
Yes, but it’s risky. A trigger could mask data quality issues. It’s better to fix the source. If you must, use a function that parses the JSON with a tool that removes duplicates (e.g., in PL/pgSQL with a language like Python via PL/Python), but test thoroughly.
Does this error occur with JSON as well as JSONB?
Yes. Both types reject duplicate keys. The difference is that JSONB stores data in a decomposed binary format for efficiency, but the validation rule is the same for both.
What if my data comes from a system that generates duplicate keys?
Pre-process the data before inserting it into PostgreSQL. Use a script to load the JSON, remove duplicates (e.g., in Python with json.loads(), which overwrites earlier keys), then re-serialize. This is safer than trying to fix it in the database.