sagold / json-schema-library

Customizable and hackable json-validator and json-schema utilities for traversal, data generation and validation
MIT License
175 stars 18 forks source link

getTemplate falsely returns default for type number when schema type is set to integer #32

Closed martensievers closed 1 year ago

martensievers commented 1 year ago

I recently bumped up my version from 4.0.0 to 7.4.4 and noticed some inconsistencies with using getTemplate.

The problem appears once I use getTemplate with input data where it seems to replace existing values of type integer with a default (0). This problem only seems to happen when the schema type is integer and works fine when the type of a property is number.

Example schema:

{
    "type": "object",
    "properties": {
        "id": {
            "type": "string"
        },
        "title": {
            "type": "string"
        },
        "students": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string"
                    },
                    "age": {
                        "type": "integer"
                    }
                }
            }
        }
    }
}

Example input data:

{
    id: '4235809c-bdc7-46c5-be3d-b1b679bb1c13',
    title: 'JavaScript Data Structures 101',
    students: [
        {
            name: 'Phil',
            age: 31
        },
        {
            name: 'Irina',
            age: 27
        }
    ]
}

My implementation looks like this:

const jsonSchema = new Draft04();
const template = jsonSchema.getTemplate(data, schema, {
    addOptionalProps: false,
});

Received output:

{
    id: '4235809c-bdc7-46c5-be3d-b1b679bb1c13',
        title: 'JavaScript Data Structures 101',
        students: [
        {
            name: 'Phil',
            age: 0
        },
        {
            name: 'Irina',
            age: 0
        }
    ]
}

Once I change the type of age to number it works fine so it seems to be related to the schema type-definition.

sagold commented 1 year ago

Hi Marten.

Thank you very much for reporting this issue.

The schema type was compared to the actual js type and thus failed for integer. This has been tested and fixed: https://github.com/sagold/json-schema-library/runs/10959229555#r0s17.

I published a version v7.4.5 including this fix.

Note that I am preparing the next major release v8. I have released a version v8.0.0-rc2 which also includes this fix. Since you are upgrading, you might want to go for v8. In case you do, pay attention to the following:

Changelog

Cheers!

martensievers commented 1 year ago

Thanks @sagold for the quick fix and yes I will be eventually updating to the latest version 👍🏼

I had actually already tested v8.0.0-rc1 before noticing the issue and it looks fine now but wanted to wait for the full release before using it in my production project 😉