What is the method for including a default value in an optional Enum item within a JSON schema?

I am configuring a JSON schema and looking to include an optional property of Enum type. In the event that the user does not provide a value for this field, I need to set a default value.

// schema
"properties" : {
    "Param" : {
        "type" : "string",
        "enum" : [ " p1", "p2" ],
        "optional" : true,
        "default" : "p2",
        "required" : true
    }
}

If the user omits the "Param" field, it will be automatically set to "p2"

Answer №1

Include the value null in the enum array

For more information, visit:

"properties" : {
    "Param" : {
        "type" : "string",
        "enum" : [ " p1", "p2", null ], // <--
        "default" : "p2", // <--
        "required" : true
    }
}

Answer №2

Just like in your example, the use of the "default" keyword in a JSON schema is valid, but its actual implementation depends on the consumer of the schema.

It's important to remember that JSON schema is primarily focused on defining and validating data structures. The inclusion of the "default" keyword came after extensive discussions because it's a common practice to provide a hint to clients regarding what a default value should be if they choose not to specify one. However, ultimately it's up to the client to decide whether or not to utilize this default value.

Another approach you could take in your specific scenario is to use "oneOf" to split enum values:

"required" : ["Param"],
"oneOf" : [{
        "properties" : {
            "Param" : {
                "enum" : ["p2"]
            }
        }
    }, {
        "properties" : {
            "Param" : {
                "enum" : ["p1", "p3"]
            }
        }
    }
]

This way, you are essentially telling the client, "You must send me at least 'Param' with the value 'p2'."

Additionally, you could consider implementing a pre-process step on your server side where any missing properties with default values are automatically added to the JSON message before validation takes place.

Answer №3

The key to solving this issue lies not in the structure itself, but rather in the processing and compilation of the data; any unspecified fields should default to a value of 0 when assigned to a variable.

For example:

   "enum" : [ "optionA", "optionB" ],

which would translate to the following in C:

enum {
 optionA = 0,
 optionB = 1
}

I hope this clarifies things for you.

Answer №4

"attributes" : {
    "Category" : {
        "type" : "string",
        "enum" : ["cat1", "cat2"],
        "default" : "cat1"
    }
},
"mandatory" : ["Category"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The jqGrid is not showing the AJAX JSON data as expected

Currently, I am exploring jqgrid and trying to figure out how to display data in another jqgrid when clicking on a specific colmodel. The retrieved data from the server goes through a function and reaches the grid, but no information is displayed without a ...

Is there a way to use getJSON to append divs and animate them one by one as they are displayed?

Hey everyone! I'm currently using a getJSON function to append some divs, but I want to make the display more dynamic. Is it possible for each div to appear milliseconds apart? For example, the first div fades in, followed by the second, and so on. H ...

Comparison between JSON Serializers and .NET Serialized Classes for Retrieving jQuery AJAX Result Data

What is the best method for transferring data from a .NET (C#, VB.NET) Web Service to the client-side using JQuery AJAX? A) Utilizing Newtonsoft JSON serialization, for example: <WebInvoke(Method:="*", ResponseFormat:=WebMessageFormat.Json, UriTemplat ...

Getting JSON data from an API using $.ajax

Currently, I am working on creating a random quote machine. To start off, I wrote the following HTML code to outline the necessary elements: <div id="quoteDisplay"> <h1 id="quote">Quote</h1> <h2 id="author">- Author</h2> ...

Utilize jQuery to extract data from a Steam page in JSON format

Although I have researched extensively on this topic, it is still not functioning as desired. I came across this Steam page in JSON format. My aim is to extract the lowest_price variable without using PHP as I am incorporating it into my Chrome extension. ...

Unsure of the response from the $.post request

CHANGE: I keep receiving the object {"readyState":1}. Why is this happening? How can I successfully retrieve the result from the $.post (specifically, the object {"result":"ERROR"})? This pertains to using jEditable. (Please note: This seems more like a ...

Exploring the intricacies of XML embedded within JSON

Utilizing YQL for jQuery, I am able to successfully execute cross-domain REST requests. The JSON response contains the desired XML data as key-value pairs. The specific request being made is: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%2 ...

$.ajax causing a JSON input string malfunction

My web API requires the following JSON format for input: [{ "atrSpaUserId": "47fe8af8-0435-401e-9ac2-1586c8d169fe", "atrSpaClassLegendId": "00D18EECC47E7DF44200011302", "atrSpaCityDistrictId": "144d0d78-c8eb-48a7-9afb-fceddd55622c"}, { "atrSpaUserId": "47 ...

Retrieving information via RESTful API using jQuery

Seeking assistance with integrating a JSON feed into an HTML document using jQuery. For instance, I am trying to extract the "base_title" and display it in an h2 tag. Any insights on how to achieve this would be greatly appreciated. Your help will be high ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...

Dynatree fails to consider the select feature while utilizing ajax requests

Currently, I am utilizing the dynatree plugin to exhibit a checkbox tree in multi-select mode (mode 3). Upon initializing the tree using ajax (without lazy loading), it appears that certain nodes that were initially loaded as selected are forgotten. When ...

Tips for transforming an html form into an ajax request for a rest controller when dealing with a multi-select field

I am encountering an issue with the field "roles" as it is a select list with multiple choices. I need to convert this field into an array, but I have not been able to find any information on how to do so. Any assistance would be greatly appreciated. Thi ...

Error 404: MVC4 Ajax request not found

When I look at the browser console, it shows a 404 error for not being able to find the URL. The URL where it's making a POST request is http://localhost:54473/Date/GetArticleName. The method inside the DateController.cs public JsonResult GetArticle ...

Error 405 - Invalid request method

Here is my JQuery code for calling a web API: let request = { RequestId: "123", DeviceId: "ACU-B2-01-R1", AccessType: "Unlock", LoginId: "tester", Password: "tester" }; $.ajax({ url: 'http://localhost:55208/api/accesspanel&ap ...

jquery struggles to understand jsonp data during cross-domain heartbeats

I have embedded my module, which is an asp.net project, within a "portal". The portal creates an iframe that points to my URL. I understand that this setup may not be ideal, but it was not something I could control. To prevent the session on the main "po ...

Transform the JSON structure with the power of JavaScript

Seeking assistance in converting the following array of JSON using either javascript or jquery: [ [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"Packet"}], [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":4 ...

Implementing Bootstrap 4 validation within a modal using JSON data

I've been struggling to validate the TextBoxFor before submitting the form. Despite trying various methods, I haven't managed to make it function properly. Modal: <div class="modal fade" id="MyModal_C"> <div class="modal-dialog" st ...

Using jQuery's `fn.each` method to generate a JSON object

In this scenario, the code is utilizing jQuery.fn.each to create a variable that will store a JSON Object. However, an issue arises when attempting to add to the array, leading to a JavaScript error. var formfields = { step: $(this).data('step') ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

Utilizing Jquery for JSON Data Parsing

I have some JSON data that looks like this: {"product":["{productTitle=ABCD , productImage=/abcd.jpg, productPath=CDEF.html, productPrice=$299}","{productTitle=EFGH, productImage=xxxx.jpg, productPath=ggfft.html, productPrice=$299}"]} In my JSP page, I&a ...