jsonSchema to validate object with random IDs for properties

Hey everyone, I am trying to figure out how can I use the jsonSchema (Schema validation — Postman Quick Reference Guide Version 1.6.10 - February 2021 documentation), to validate a response body that consists of the following example:

{
    "Role": {
        "16": {
            "id": 16,
        },

        "108": {
            "id": 108,

        },
}

We have a nested object and trying to follow up the documentation I linked above, I get stuck at those random IDs for each object. How can I write something for those properties?

const expectedData = 
{
    "type": "object",
    "properties":{
        "Role": {
            "type":"object",
            "properties":{
                "16": {
                    "type":"object",
                    "properties":{
                        "id": {
                            "type": "number", "null"
                    }   
                }
        }
    }
}

Ignore the details, the piece above is not ready, just the structure is what I am interested in.

Hi @bezzea,
Welcome :smiley:
I found this - jsonschema - JSON Schema for object with keys of random numbers - Stack Overflow and this - object — Understanding JSON Schema 7.0 documentation

With pattern properties, the key is matched to a regex and the schema can be validated for that regex key. Hope that can solve the issue.

Thanks for posting, I learned something new today :nerd_face:

2 Likes

Hello and thanks for your answer,

Not really sure if I understood it correctly, this is what I came up with and it still throws an error:

There was an error in evaluating the test script: SyntaxError: Unexpected token ‘}’

const response = pm.response.json()
const expectedData = 
{
    "type": "object",
    "properties": {
        "Role": {"type": "object"},
            "patternProperties": {
                "^[0-9]+$": {"type": "integer"},
                    "id": {"type":"number"},
            }
    }
}

pm.test("Received", function(){
    pm.response.to.have.jsonSchema(expectedData)

})

Could this be because my IDs are indeed strings, but I expect postman to read those ID’s as objects?

I have also noticed that I told postman to expect for each properties a series of numbers,strings between the object braces and that I believe is wrong.

EDIT:
Solved the problem by adding another type for properties between {} like so "originDate": {"type":["string","null"]},
It had to see the second type instead of just adding the types one after another with comma symbol.

1 Like

Glad you found the solution! I marked it so that other Postman users can find this. I’m also moving the thread over to help.

Welcome to the community, @bezzea !