•

AI JSON Intake: Reject Duplicate Keys Before Routing

Two grayscale metal keys approach one keyhole held by a hand, with separate muted paths pausing before convergence.
What’s in this article?

    Reject conflicting JSON field names before they become routing decisions. Use a scoped parser gate, test fixtures and a correction path that preserves what actually arrived.

    An AI request can arrive as apparently ordinary JSON while carrying two different values for the same field. If one component checks the first value and another uses the last, the workflow can act on something different from what it approved.

    For operations teams, the practical question is not whether an AI model can explain the conflict. It is whether the intake boundary preserves enough information to detect it before a model, reviewer or execution service receives a simplified object.

    This guide shows how to reject duplicate JSON keys in an AI-assisted request pipeline. It complements schema design for LLM structured outputs: a schema defines acceptable fields and values, while the parsing boundary must first establish which fields actually arrived.

    One object must not carry two meanings for one field

    Consider this constructed service-request payload:

    {"request_id":"SR-42","review_required":true,"review_required":false}

    Do not choose the more convenient value, and do not ask AI to select the intended one. Return a duplicate-name disposition and prevent interpretation or execution until a corrected revision arrives.

    RFC 8259, section 4 recommends unique names within an object and describes differing receiver behavior when names repeat. A duplicate is therefore not necessarily a JSON grammar error; your application needs an explicit admission policy. The narrower I-JSON object constraints prohibit duplicates and compare names after escape processing. Rejecting duplicate names alone does not establish full I-JSON compliance.

    Scope matters. The name status can appear once in each of two separate request objects. The conflict is repetition within the same object, including an object nested inside an array. Escaped and literal spellings of the same decoded name also count as repetition.

    Put the check before information is discarded

    Preserve input, then admit one interpretation

    Use the following recommended boundary for JSON entering an AI workflow:

    1. Receive bounded input. Enforce the interface’s body-size, encoding, nesting and time limits. Authenticate the sender where required. If a protocol signs original bytes, verify exactly those bytes before any transformation.
    2. Parse with duplicate detection. Compare decoded names within each object before converting its pairs into a dictionary or ordinary map.
    3. Validate the admitted object. Apply schema, allowed-field, identifier, tenant and authorization rules. Duplicate detection does not replace these controls.
    4. Supply authorized context to AI. The model may interpret the request or propose a classification. It must not decide which contradictory raw member to retain or grant its own action authority.
    5. Validate recommendations and route work. Rules and named humans determine permitted transitions. A separate execution system performs authorized actions and records their outcomes.

    Run an equivalent gate on serialized JSON returned by an adapter or tool before that output influences another decision. Do not assume every upstream component preserves the same information.

    If middleware has already collapsed the payload into a map, a later schema check cannot recover discarded pairs from that map alone. Locate the earliest controllable parsing boundary. Until the raw-input behavior is understood, do not report duplicate-name coverage as passed.

    Keep parser and business-policy failures separate

    A duplicate field is a representation conflict. A valid object naming an unauthorized approver is a business-policy failure. A parser service that is unavailable is an infrastructure failure. These need different dispositions, even when all three prevent the next action.

    Test the entire intake-to-consumer path, not just a parser in isolation. For each fixture, compare the admitted interpretation with what the final consumer would act on. A passing test at the first layer is insufficient if a later component reparses the original text differently.

    A small Python gate that detects nested duplicates

    The Python JSON documentation explains that default decoding retains the last value for repeated names and exposes object_pairs_hook for changing that behavior. The following illustrative gate rejects repeated decoded names before constructing each dictionary:

    import json
    
    class DuplicateName(ValueError):
        pass
    
    def unique_object(pairs):
        result = {}
        for name, value in pairs:
            if name in result:
                raise DuplicateName("duplicate_object_name")
            result[name] = value
        return result
    
    def reject_constant(value):
        raise ValueError("nonstandard_number")
    
    def decode_request(text):
        value = json.loads(
            text,
            object_pairs_hook=unique_object,
            parse_constant=reject_constant,
        )
        if not isinstance(value, dict):
            raise ValueError("top_level_object_required")
        return value

    The hook operates on each decoded object, including nested objects. The example also rejects Python’s accepted nonstandard numeric constants and requires a top-level object as an application rule. It is not a complete secure JSON receiver: transport authentication, resource limits, Unicode policy, numeric range checks, schema validation and authorization remain separate work.

    Do not implement this check with a regular expression over the text. A name can contain an escape, and repeated field names in different objects are legitimate. Nor should you silently lowercase all names: exact decoded equality and application-specific alias or case matching are distinct concerns. Define allowed canonical field names and reject unexpected aliases in the contract layer.

    This minimal hook returns a stable reason code rather than including raw field values in the exception. A production diagnostic may need a safe object path or source offset; obtain it from suitable parser instrumentation. Do not invent precise locations that this example does not capture.

    Make correction a new revision, not an automatic retry

    Persist a disposition outside the interpretation/action path. A rejected payload should not create an executable business request merely to give the rejection somewhere to live.

    StateRequired evidenceNext permitted step
    ReceivedAuthenticated source where applicable, receipt ID, bounded input reference and content digestRun the configured parser gate
    Rejected: duplicate nameParser policy/version, stable reason, receipt and restricted original-input referenceRequest a corrected revision; no model call or action
    Held: verifier unavailableFailure category, existing receipt, accountable platform ownerBounded recovery on the same input after service restoration; never bypass the gate
    AdmittedSingle parsed interpretation, schema/policy versions and checksInterpret with authorized context, then validate the result
    Corrected revision receivedNew receipt/revision linked to the rejection, source authority and resubmission evidenceRepeat admission and business checks; do not inherit approval
    ClosedConfirmed outcome, correction link or explicit abandonment/rejectionRetain evidence under the agreed access and retention policy

    In the service-request example, the first revision is rejected before AI sees it. The source owner resubmits a revision with one review_required member. That removes the representation conflict; it does not establish whether review can actually be skipped. The application’s policy still determines that decision, independently of the supplied flag.

    Record source-scoped receipt identity separately from the business request identifier. A repeated transport delivery of one revision should find its existing disposition. A corrected revision must remain distinguishable, even if its business identifier is unchanged. Define those identities in your interface rather than using a digest alone as proof of authority.

    If execution later times out, reconcile the existing authorized operation using its original action identity before considering a retry. Parsing success is not execution success. Human rejection closes or returns the business request according to policy; it must not trigger a model retry intended to find a more favorable recommendation.

    Use a release matrix that proves the boundary

    Run these recommended fixtures with synthetic data in a controlled environment. The expected behavior is a design target; a local parser demonstration does not prove your deployed gateway, queue and consumer share it.

    FixtureExpected resultEvidence to retain
    One unique member per objectPass parsing; continue to independent business checksBaseline interpretation and route
    Same name twice with conflicting values, in both ordersReject both before model or actionRejection and zero downstream invocations
    Same name twice with identical valuesReject; equality of values does not waive the admission policyStable duplicate-name disposition
    Literal name and equivalent Unicode escapeReject after decoded-name comparisonOriginal fixture and parser result
    Duplicate inside an object within an arrayReject the whole request under this interfaceNested-case rejection
    Same name once in each of two different objectsNo duplicate-name rejectionFalse-positive control
    Case variant or unsupported aliasApply the explicit field-name contract; no accidental consumer overrideSchema/consumer agreement
    Unavailable verifier, repeated delivery, corrected revisionHold without bypass; reuse prior disposition; recheck the correctionLinked lifecycle records and no duplicate effect

    Assign the parser fixtures to engineering, the routing and authority expectations to the workflow owner, and the retention/access rules to the responsible data owner. Re-run the relevant suite after parser, SDK, middleware or consumer configuration changes.

    Measure duplicate-name rejections over received JSON revisions, unavailable-verifier holds over received revisions, and false rejections over independently reviewed samples. Track model calls or actions originating from rejected fixtures as explicit failures. Define the observation window and denominators; a low rejection count alone is not evidence that the check works.

    Where Workhint fits

    Workhint’s Workflow Engine describes configurable approval routing and required details or files before work advances. These capabilities are relevant to designing the human review handoff after a JSON receiver has established one admissible interpretation.

    The Workflow Automation Software solution describes structured forms, conditional routing, stages and assigned reviewers. That supports a discussion about who handles a correction and what information permits the next step. Neither page establishes a native duplicate-key parser, a particular JSON integration, or the receiver guarantees proposed here. Validate that technical boundary separately.

    Frequently asked questions

    Can JSON Schema detect duplicate keys after parsing?

    Not from an ordinary map that has already discarded repeated members. Detect them while parsing the serialized input, then validate the admitted object against the schema.

    Should AI repair a payload with duplicate names?

    Not as an automatic admission step for operational actions. Preserve the rejection and obtain an authorized corrected revision. A plausible repair is not evidence of the source’s intent.

    Are repeated names in separate objects duplicates?

    No. The duplicate-name rule is scoped to an individual object. Separate objects may each contain the same field name once.

    What should block release?

    Block release if conflicting or escaped duplicate names reach AI or execution, if middleware discards evidence before the gate, if verifier outages bypass admission, or if corrected revisions inherit an approval that has not been revalidated.

    Comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *


    The reCAPTCHA verification period has expired. Please reload the page.