THE PRACTICAL GUIDE

What different JSON readers do with duplicate object names

Compare one ambiguous currency field in JavaScript, Python, and SQLite. Detect repeated names before conversion and choose a representation both ends can read.

How we checked this guide. We compared JavaScript, Python’s ordered-pair hook, and SQLite’s JSON rows using the same duplicate names and checked the members each retained. Editorial and testing standards

Which currency did the sender choose?

An exported price has an amount of 12 and two fields named currency. One says EUR and the other says GBP. A preview panel pairs the amount with GBP. Someone inspecting the raw export sees EUR first and reads the amount as euros. The two interpretations can survive a grammar check because the punctuation, strings, and number are all legal JSON. Choosing the currency is a decision about the record that its punctuation cannot settle.

Use the small fixture below to discover what each reader exposes. Copy the original into each experiment independently. Passing JavaScript's reconstructed object to Python would remove evidence before the second experiment starts. For a visual cross-check, format the original with ADEMN and locate both currency members under the same pair of braces. Their positions make the disagreement easy to see, although their positions do not establish which currency a producer intended.

Price record as supplied to each reader
{"amount":12,"currency":"EUR","currency":"GBP"}

Compare lookup, enumeration, and rejection

JavaScript's JSON.parse returns an ordinary object here. Looking up its currency property yields GBP. Python's json.loads gives the same answer with the default dictionary result. Python can also call an object_pairs_hook with the members in input order, before building the dictionary. That allows the receiver to inspect both currency entries or stop the import with a precise error. The choice of data structure changes what evidence remains available after a successful parse.

SQLite offers another way to inspect the fixture. Pass the text itself to json_each and select its key and value columns. On SQLite 3.51.0 the query below returns two rows for currency, one for EUR and one for GBP. This observation concerns that function and the supplied text. Verify the behavior of the particular database function and version in your own read path, especially if an intermediate step rewrites JSON before the query runs.

JavaScript property lookup
const raw = '{"amount":12,"currency":"EUR","currency":"GBP"}';
console.log(JSON.parse(raw).currency); // GBP
Python 3 member enumeration
import json
raw = '{"amount":12,"currency":"EUR","currency":"GBP"}'
print(json.loads(raw, object_pairs_hook=list))
# [('amount', 12), ('currency', 'EUR'), ('currency', 'GBP')]
SQLite member enumeration
SELECT key, value
FROM json_each('{"amount":12,"currency":"EUR","currency":"GBP"}')
WHERE key = 'currency';

Compare decoded names inside each object

A duplicate check operates at an object boundary. Two array elements may each contain one currency field because each belongs to a separate object. Likewise, billing.currency and shipping.currency name different members. A document-wide tally of field names would flag these ordinary cases. The set of names already seen must belong to the object currently being parsed. Allocate a fresh set for each object, including objects nested inside arrays.

Spelling in the source text can obscure equality. A key spelled with a Unicode escape for its first character decodes to the same name as the literal key. The middle row of the table uses a backslash followed by u0063, which represents a lowercase c. Scanning raw text for two literal copies of the word currency misses that pair. Conversely, Currency and currency are distinct JSON strings. An application that requires lowercase field names can reject the capitalized spelling in a separate schema check.

Decide whether names repeat in the same object
Original inputDuplicate?Reason
[{"currency":"EUR"},{"currency":"GBP"}]NoEach array element has its own object.
{"currency":"EUR","\u0063urrency":"GBP"}YesThe two decoded names both spell currency.
{"Currency":"EUR","currency":"GBP"}NoUppercase C and lowercase c are different characters.

Put a duplicate check where it can still see both values

The following Python function rejects the second occurrence as it constructs each object's dictionary. It raises an exception even when the two values are equal. That rule makes the producer contract testable without deciding whether repeated but equal values are harmless today. If the call succeeds, later code receives a normal dictionary and can validate the amount and currency types. Python's regular dictionary conversion would discard the earlier field before a validator could inspect it.

Run the example with each input from the table. The first should yield a list of two objects, the second should raise ValueError, and the third should keep two differently capitalized keys. Put the same checks in front of any normalization step that turns the document into a map. For a large batch, capture an independent record identifier and the offending name when you reject a row. Those are usually enough for the producer to find it without putting a full payload in a shared error report.

When comparing the reject policy with a downstream service, also send a fixture whose two fields both contain EUR. A reader which always keeps the last field will appear to agree about the currency. The strict receiver still rejects it, which exposes a difference in acceptance that a value-only comparison would miss. Save whether the input was accepted alongside any currency that was returned.

Reject repeated decoded names using Python's standard library
import json

def unique_members(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Repeated JSON name: {key}")
        result[key] = value
    return result

raw = '{"amount":12,"currency":"EUR","currency":"GBP"}'
json.loads(raw, object_pairs_hook=unique_members)
# ValueError: Repeated JSON name: currency

Represent the meaning the producer actually needs

Ask the exporter what the two currencies describe. A single advertised price has one currency and one amount. If the second field came from a default configuration appended after a row override, resolve that precedence in the exporter and send one currency. Reverse the order of fields in a test fixture as well. The same semantic record should survive serialization regardless of the order in which a library visits the remaining unique members.

A price list for multiple markets needs a different shape. Give each amount a currency inside a separate entry, as shown below. If order carries business meaning, document how consumers should use the order of those array entries. If only one price per currency is allowed, validate that constraint across the array. A duplicate-name check alone cannot catch two entries that both happen to sell the item in euros.

RFC 8259 recommends unique object names for interoperability. The stricter I-JSON profile requires them. Record which rule your interchange agreement follows, and test the agreement at ingestion using the raw fixture. An export that has already been parsed and rewritten can look perfectly clean while containing only the last value that a previous reader retained.

Two market prices with a currency attached to each amount
{"prices":[{"amount":12,"currency":"EUR"},{"amount":10,"currency":"GBP"}]}

Methods and references

Put it into practice