Validate a nested dictionary using python/marshmallow when field names are variable

23 Views Asked by At

Given this example...

{
  "A-B": {
    "x": {
      "name": "x A-B"
    },
    "y": {
      "level": 6
    }
  },
  "B-C": {
    "x": {
      "name": "x B-C"
    },
    "y": {
      "level": 9
    }
  },
  "A-C": {
     "x": {
        "name": "x A-C"
    }
 }
}

Where "A", "B" and "C" are states and "x" and "y" are different dicts. "x" can have a "name" key with a string value amd "y" can have a "level" key with an integer value.

Both "x" and "y" are optional.

I've create the schemas for "x" and "y"...

def X_Schema( Schema ):
  name = fields.String( required = True )

def Y_Schema( Schema ):
  level = fields.Integer( required = True )

I know I need to use some nesting but I can't work out how this is going to work when the top level "key" is not fixed. i.e. it can be "A-B", "A-C", "B-C" etc. "x" and "y" can only occur once within a top level value, both are optional.

I'd like to do something like...

def StateSchema( Schema ):
  ???? = fields.Dict( keys = < "x" or "y" >, values = <X_Schema or Y_Schema> )

Personally, I don't think this is possible using marshmallow. I do not control this input so I'm pretty much stuck not validating it if can't be done using marshmallow.

I've got this far...

class StateSchema( Schema )

  a_b = fields.Dict( keys = fields.String(), values = fields.Nested( X_Schema() ), required = False, data_key = "A-B" )

  b_c = fields.Dict( keys = fields.String(), values = fields.Nested( X_Schema() ), required = False, data_key = "B-C" )

but I feel this is sub-optimal as I need to create fields for all of the possible states.... :(

0

There are 0 best solutions below