jdorn / json-editor

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

changing schema based on selection/data #619

Closed brean closed 3 years ago

brean commented 8 years ago

Hi,

in my current JSON-Editor Project I have a field labeled "type" that allows the user to select a type. Depending on what he chooses from that it should be possible to enter different things. Is it possible to have that in one schema and editor or do I have to create a new editor with a second schema that is based on the selection of the first editor (using editor.on('change'... on the first editor)?

codler commented 8 years ago

I wonder also

wjy4124 commented 8 years ago

I wonder also too..

jdorn commented 8 years ago

This is possible with JSON Schema, but it's counter-intuitive. The trick is to use a combination of oneOf, additionalProperties, and enum with a single value

Here's an example:

{
  "type": "object",
  "properties": {
    "type": {
      "type": "string",
      // Hide the 'type' input. Using 'oneOf' will give the user another way to switch between types
      "options": {"hidden": true}
    }
  },
  "oneOf": [
    {
      "title": "Full Name",
      "additionalProperties": false,
      "properties": {
        "type": {
          "type": "string",
          "enum": ["fullName"]
        },
        "fullName": {"type": "string"}
      }
    },
    {
      "title": "First and Last Name",
      "additionalProperties": false,
      "properties": {
        "type": {
          "type": "string",
          "enum": ["first-last-name"]
        },
        "firstName": {"type": "string"},
        "lastName": {"type": "string"}
      }
    }
  ]
}
fxi commented 8 years ago

@jdorn using 0.7.28, this example returns the type inconsistently. I was expecting the type to be returned each time, but it's not the case. Example

[ edit ] I "solved" my issue using properties of type "boolean" with different name (e.g "type_a" : true for the first oneOf and "type_b": true for the second. Example ) and I will adapt by code.

Thanks :)

abop commented 7 years ago

@fxi I dug into the source and found that the problem was caused by the option keep_oneof_values, of which the default value is true. Set it to false would solve the problem.

JSONEditor.defaults.options.keep_oneof_values = false;

@jdorn Maybe it should be added to doc as an FAQ.

fxi commented 7 years ago

@abop : Yep, keep_oneof_values = false ; solves this problem. Example. Thanks!