jdorn / json-editor

JSON Schema Based Editor
MIT License
5.8k stars 1.08k forks source link

Changing Refs (oneOf) retains additional values. #318

Open mscuthbert opened 9 years ago

mscuthbert commented 9 years ago

In this schema (borrowed from a solved issue), the object should validate against one of A or B, that is, have an "a" or "b" property. But in switching from A (a sensible default) to B, the a property is retained. Is there a way that on switching from A to B the a property is deleted? People using the editor I'm creating won't want the b property if they've chosen schema A. Thanks for an AMAZING tool. If you could even point to where in the code the switch of schemas takes place I should be able to write an option for deleting existing properties.

 {       
            "title": "root",
            "type": "object",
            "oneOf": [
                {"$ref": "#/definitions/A"},
                {"$ref": "#/definitions/B"}
            ],
            "definitions": {
                "A": {
                    "title": "A",
                    "type": "object",
                    "properties": {"a": {"type": "string"}},
                    "required": ["a"]
                },
                "B": {
                    "title": "B",
                    "type": "object",
                    "properties": {"b": {"type": "string"}},
                    "required": ["b"]
                }
            }
        }

Direct link:

http://jeremydorn.com/json-editor/?schema=N4IgLglmA2CmIC4QCcD2qwgDTgJ4Ad4lUAjAK1gGNMdUA7WAeQDNEBtUSGIkAQWzyFEIUhWoD8aQskiwAzolABDRYJ5ywyCHQDmIAL76cyWAEcArhBMATdiBUBdHNdjNtUCPQUJQ/H+Cg4YX4cMAIeUSoaEElUaVlvZVUwoSQNLV0DIxQzSxs7R2yAIWTAnhLQ8OFI8RxY+Ih5VRJkqrTNbT1DY1yrWFsENhAWh0MjTjLhCrVq8iiJKVgZRsTh1tSQdM6snos+gaGR51d3SC9VPwnuYIEUiLnamMXlpv8VfzvhLczunL38wb2ECjHAlD6TJDTT7EB7RepLBLNdbqDo/bImf79OwjMZOEAuNx0DznfyXALXJAhGYwsRw56It7Ir6orro3oAoaFUGlCkgKFtESwhZxBErJEfAXfVm7PJYwE4wxAAA=&value=N4IghiBcIgvkAA==&theme=bootstrap2&iconlib=fontawesome4&object_layout=normal&show_errors=interaction

Kestrel12 commented 9 years ago

I've fixed this in this pull request: https://github.com/jdorn/json-editor/pull/319. The issue was that the editor was doing a setValue that tried to set the value of fields that weren't necessarily on the form, causing them to be added. I should maybe go back and make the setValue merge the fields that are present, but hopefully this works for you.

jdorn commented 9 years ago

I just added a new option keep_oneof_values. It defaults to true to keep the current behavior, but you can set it to false to do what you want.

Set globally:

JSONEditor.defaults.options.keep_oneof_values = false;

Set per JSONEditor instance:

var editor = new JSONEditor(el, {
  schema: {...},
  keep_oneof_values: false
});

Set for a single oneOf instance:

{
  "options": {
    "keep_oneof_values": false
  },
  "oneOf": []
}
mbrodala commented 9 years ago

This can be closed by now.