json_schemer icon indicating copy to clipboard operation
json_schemer copied to clipboard

Can't insert property defaults when using definitions

Open rquant opened this issue 1 year ago • 3 comments

Hi I am trying to create a re-usable definition in my schema, that contains some property defaults. Here is an example of my schema:

{
    "type": "object",
    "properties": {
      "email": {
        "$ref": "#/definitions/notification_setting"
      }
    },
    "definitions": {
      "notification_setting": {
        "type": "object",
        "properties": {
          "enabled": { "type": "boolean" },
          "deprecated": { "type": "boolean" }
        },
        "default": {
            "enabled": true,
            "deprecated": false
        }
      }
    }
  }

The issue is it doesn't appear the references are being resolved, and I'm not seeing default values being inserted into my empty hash:

irb(main):080:0> schema
=> {"type"=>"object", "properties"=>{"address"=>{"$ref"=>"#/definitions/address"}}, "definitions"=>{"address"=>{"type"=>"object", "properties"=>{"street"=>{"type"=>"string"}, "city"=>{"type"=>"string"}}, "default"=>{"street"=>"123 abc st", "city"=>"funky town"}}}}
irb(main):081:0> data = {}
=> {}
irb(main):083:0> JSONSchemer.schema(schema, insert_property_defaults: true).valid?(data)
=> true
irb(main):085:0> puts data
{}

Any idea on why this doesn't work? Do I need to provide a custom ref_resolver?

Thanks!

rquant avatar Feb 16 '24 19:02 rquant

It does not depend on ref_resolver, this schema uses only local json pointers. Seems like a bug with object + default or with $ref + default.

ekzobrain avatar Feb 22 '24 16:02 ekzobrain

Thanks for opening this, @rquant! Looks like refs aren't followed when checking for default values. I'm working on a fix now.

davishmcclurg avatar Feb 25 '24 19:02 davishmcclurg

@rquant I just opened a PR to address this: https://github.com/davishmcclurg/json_schemer/pull/175 Do you mind trying it out to make sure it works for you?

davishmcclurg avatar Feb 25 '24 21:02 davishmcclurg

Fix has been merge and will be released shortly in 2.2.0. Original example works now:

?> schema = {
?>   "type": "object",
?>   "properties": {
?>     "email": {
?>       "$ref": "#/definitions/notification_setting"
?>     }
?>   },
?>   "definitions": {
?>     "notification_setting": {
?>       "type": "object",
?>       "properties": {
?>         "enabled": { "type": "boolean" },
?>         "deprecated": { "type": "boolean" }
?>       },
?>       "default": {
?>         "enabled": true,
?>         "deprecated": false
?>       }
?>     }
?>   }
>> }
=>
{:type=>"object",
...
>> data = {}
=> {}
>> JSONSchemer.schema(schema, insert_property_defaults: true).valid?(data)
=> true
>> puts data
{"email"=>{"enabled"=>true, "deprecated"=>false}}
=> nil

davishmcclurg avatar Mar 02 '24 21:03 davishmcclurg