2

Consider a "complex" schema which uses references from other files like the one below. Is there a simple way to get a list of all properties defined in a schema, perhaps using some of the machinery already in python-jsonschema? I think I only need properties at the top level, but a generalizable approach would be great.

There are numerous applications I need this for, but basically I need to be able to run different operations on only those 'properties' of objects matching the schema which are defined in the schema (so that I don't also apply these operations to any additional properties not defined in the schema). For example, lets say I want to print the value of every property than an object has, that is defined in the schema. To do that I need a list of the properties the schema defines. Another example would be if I want to compare two objects based only on the schema-defined properties.

{
    "$schema": "http://json-schema.org/schema#",

    "allOf": [
        {
            "$ref": "file:/some/file.json"
        }
    ],

    "properties": {
        "a": {
            "type": "string"
        }
    }
}

Example application:

# Load an object that has attributes conforming to the schema in `schema`
obj = Schema_Conforming_Object(schema)

# Get a list of all properties defined in the schema
#    This is what I'm not sure how to do nicely
props = properties_of_schema(schema)

for pr in props:
    if pr in obj:
        print(obj[pr])
DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119
  • What are you trying to achive here? Complex schemas will have many layers of properties, nested in conditional applicators, so it's hard to give you an answer to this without the context of why you want to do this. – Relequestual Jul 18 '18 at 08:14
  • 1
    @Relequestual you're right, that was too vague. I've added some more info that I hope clarifies things better – DilithiumMatrix Jul 18 '18 at 18:35
  • Thanks for updating. This isn't a common use case, so it's unlikely to be baked into a library which is for validation purposes. If you know that all the properties will be at the root properties object level, you can extract them easily enough. If there are many nested and referenced objects, that becomes a harder problem. - In answer to your question... no. The validators that provide verbose details on validation results only do so on error. – Relequestual Jul 19 '18 at 08:44
  • @Relequestual I was coming to the same conclusion. I tried using a reference resolver (built into the python jsonschema package) to generate a de-references single schema, but still ran into issues with some `properties` being on the top level explicitly and others (which apply to the top level) being inside logical statements (e.g. `allOf`) making it still non-trivial to extract a list. I think I'm going to restructure the schema to approach the problem another way – DilithiumMatrix Jul 19 '18 at 15:22

0 Answers0