question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Requiring one of two properties to exist but not both

See original GitHub issue

Describe the bug Attempting to define a constraint where only one of two properties should exist but not both.

To Reproduce

Example schema:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "type": "object",
    "properties": {
        "ReqHeader": {
            "type": "object",
            "properties": {
                "AThing": {
                    "type": "object",
                    "properties": {
                        "A_prop1": {
                            "type": "string"
                        },
                        "A_prop2": {
                            "type": "string"
                        }
                    }
                },
                "BThing": {
                    "type": "object",
                    "properties": {
                        "B_prop1": {
                            "type": "string"
                        },
                        "B_prop2": {
                            "type": "string"
                        }
                    }
                }
            },
            "oneOf": [
                {
                  "required": [
                    "AThing"
                  ]
                },
                {
                  "required": [
                    "BThing"
                  ]
                }
              ]
        }
    },
    "required": [
        "ReqHeader"
    ]
}

Used commandline:

datamodel-codegen --input test.json --input-file-type jsonschema --output test.py --target-python-version 3.6

Resultant output:

# generated by datamodel-codegen:
#   filename:  test.json
#   timestamp: 2021-08-11T15:37:19+00:00

from typing import Any, Union

from pydantic import BaseModel


class Model(BaseModel):
    ReqHeader: Union[Any, Any]

Expected behavior A clear and concise description of what you expected to happen.

  • Have all of the objects created in the output module
  • A constraint to enforce existence of AThing or BThing but not both.

Example input scenario expectations: Scenario: AThing Only (OK)

{
    "ReqHeader": {
        "AThing": {"A_prop1": "val", "A_prop2": "val"}
    }
} 

Scenario: BThing Only (OK)

{
    "ReqHeader": {
        "BThing": {"B_prop1": "val", "B_prop2": "val"}
    }
} 

Scenario: BThing and AThing (Not OK)

{
    "ReqHeader": {
        "AThing": {"A_prop1": "val", "A_prop2": "val"},
        "BThing": {"B_prop1": "val", "B_prop2": "val"}
    }
}

Version:

  • OS: CentOS Linux release 7.6.1810 (Core)
  • Python version: 3.6.8
  • datamodel-code-generator version: 0.11.9

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

3reactions
tseadercommented, Aug 12, 2021

Works great - many thanks to you @koxudaxi for your help. StackOverflow unfortunately provided a different path that I tried, which functionally meets json-schema standards and pans out as far as the OK/NOT-OK scenarios above, but didn’t reflect well in Pydantic.

To summarize - the idea is to create encapsulation objects [ReqHeaderA and ReqHeaderB] for each choice so that the property name in the encapsulation object(s) [AThing and BThing in my scenario] can be appropriately exposed/used.

1reaction
hypogealgaolcommented, Apr 26, 2022

I have a similar use case, except that I want it to be one of two properties, either, but not none. I am getting the same result with the Union[Any, Any] but unsure if it is because of how the JSON schema is defined.

for example, I want to be able to have two string properties A and B be validated, where the only validation failure is when neither are present.

A json schema with a field definition after properties where A and B are defined, such as

"anyOf": [
               {
                    "required": [
                        "A"
                    ]
                },
                {
                    "required": [
                        "B"
                    ]
                }
            ],

generates a model where both A and B are just Optional[str] and not one where the non-presence of both fails validation, despite that occurring when the json validation runs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

typescript interface require one of two properties to exist
Hi guys, how do you force to choose between one of the interfaces, but not both? With that type, an object with both...
Read more >
Requiring One of Two Properties to Exist in TypeScript
We use the "never" keyword to indicate that one property should not be set at the same time as the other. The or...
Read more >
Typescript type shenanigans 2: specify at least one property
Given some type with n properties and z optional properties, I want a type that expresses that someone must specifiy at least one...
Read more >
RequireAtLeastOne type alias
RequireAtLeastOne helps create a type where at least one of the properties of an interface (can be any property) is required to exist....
Read more >
Handbook - Unions and Intersection Types
Intersection and Union types are one of the ways in which you can compose types. ... Property 'swim' does not exist on type...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found