Extract the necessary fields from the JSON Schema

I am in search of a solution to extract the required fields from a JSON Schema and Data combination.

Currently, we are utilizing AJV for getting error messages in our forms using JSON Schema, and it has been performing really well.

I am looking for a method to retrieve all the required fields (even if already filled) so that I can label those fields with * as "required". The required fields may vary depending on the schema and data combinations.

I also attempted to extract the required fields using tv4, but without success.

Your assistance would be greatly appreciated.


Here is an example of such a schema:

{
  "type": "object",
  "required": [
    "checkbox"
  ],
  "properties": {
    "checkbox": {
      "type": "boolean"
    },
    "textbox": {
      "type": "string"
    }
  },
  "oneOf": [
    {
      "required": [
        "textbox"
      ],
      "properties": {
        "checkbox": {
          "enum": [
            true
          ]
        }
      }
    },
    {
      "properties": {
        "checkbox": {
          "enum": [
            false
          ]
        }
      }
    }
  ],
  "additionalProperties": false
}

Answer №1

After reviewing your inquiry, the most straightforward approach to achieve your desired outcome would be:

  1. Retrieve the Json data when the page loads,
  2. Go through the json data to eliminate valid values (refer to example 1),
  3. Invoke tv4.validateMultiple(data, schema),
  4. Inspect the result object and retrieve the necessary fields (refer to example 2).

example 1

for(let prop in data) {
    if(data.hasOwnProperty(prop)) {
        //assign a null value, -1, or any other universally undesirable value
        data[prop].value = null;
    }
}

example 2

let result = tv4.validateMultiple(data, schema);
let required = result.errors;

Answer №2

The issue was resolved through the following steps:

  1. We decided to fork tv4 (renamed as tv4 - for ease of editing) by visiting the link below:

    https://github.com/mikila85/tv4

    We then generated an array of "Requireds".

  2. Next, we proceeded to iterate through each required field, resetting its data and forwarding the data+schema to AJV for validation (opted for AJV over tv4 due to quicker parsing).

This approach allowed us to identify which specific required fields were necessary for the provided data.

Below are the functional implementations we crafted (though not the most polished, they serve their purpose well):

function getAllRequiredFields() {
    var allRequiredFields = tv4.validateMultiple($scope.formModel, $scope.formSchema).requireds;
    allRequiredFields = allRequiredFields.filter(function onlyUnique(value, index, self) {
        return self.indexOf(value) === index;
    });

    return allRequiredFields;
}

function getRequiredFields() {
    var t0 = performance.now();

    // This function should be invoked on every model change for optimal performance as it utilizes tv4's data+schema optimization.
    var allRequiredFields = getAllRequiredFields();
    angular.forEach(allRequiredFields, function (requiredPath) {
        var modelWithDeletedRequiredProperty = angular.copy($scope.formModel);

        deleteValue(modelWithDeletedRequiredProperty, requiredPath);
        if (!validateForm(modelWithDeletedRequiredProperty)) {

            var requiredError = getErrorObjectsArray(validateForm.errors).find(function (error) {
                return error.path === requiredPath;
            });

            if (requiredError) {
                localValidation[requiredError.inputName] = localValidation[requiredError.inputName] || {};
                localValidation[requiredError.inputName].isRequired = true;
                requiredFieldsPath.push(requiredError.inputName);
            }
        }
    });

    var t1 = performance.now();
    console.log("form checking took " + (t1 - t0) + " milliseconds.");
}

Answer №3

This particular function is designed to retrieve schema indices in a recursive manner, offering the possibility for customization.

   // https://github.com/pubkey/rxdb/blob/master/src/rx-schema.js
 export function obtainIndices(schemaJSON, previousPath = '') {
        let schemaIndexes = [];
        Object.entries(schemaJSON).forEach(entry => {
            const key = entry[0];
            const obj = entry[1];
            const path = key === 'properties' ? previousPath : util.trimDots(previousPath + '.' + key);

            if (obj.index)
                indexes.push([path]);

            if (typeof obj === 'object' && !Array.isArray(obj)) {
                const additionalIndices = getIndexes(obj, path);
                schemaIndexes = schemaIndexes.concat(additionalIndices);
            }
        });

        if (previousPath === '') {
            const additionalCompoundIndices = schemaJSON.compoundIndexes || [];
            schemaIndexes = schemaIndexes.concat(additionalCompoundIndices);
        }

        schemaIndexes = schemaIndexes
            .filter((element, position, array) => array.indexOf(element) === position); // unique;
        return schemaIndexes;
    }

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

Decoding JSON with JavaScript following the response from JsonConvert.SerializeObject(json) in a .NET handler

I am currently working on a web application using the .NET platform. I have written a Handler code that returns a JSON object to JavaScript (after making an AJAX request). Here is the Handler code: var wrapper = new { left = left.ToString(), t ...

Visualizing link values in Les Miserables using d3.js in Co-occurrence demo

I am currently working on injecting my own data into a different example. Take a look at the following link: I am creating my own JSON files for this purpose. However, I am struggling to grasp how the links values are transformed into colors, particularly ...

Struggling with passing data to a child component in React

I am currently working on a gallery project where users can click on an image to view it in a separate component using props. The images are sourced from a hardcoded array, and the challenge lies in connecting this data to the component accurately. I have ...

Error Encountered in jQuery UI SelectMenu

Struggling to integrate the jQuery UI SelectMenu, I keep encountering the same error in the browser console. Below is the HTML Code: <select name="files" id="files"> <optgroup label="Scripts"> <option value="jquery">jQuery.js</ ...

Displaying tooltips dynamically for newly added elements all sharing a common class in React

I'm facing an issue with the primereact tooltip component from . Everything seems to be working fine except for the target property. When I have multiple elements on a page with the same class, the tooltip works as expected. However, when I add a new ...

Executing multiple commands using Node.js TCP communication

I have established a connection to a serial device via the internet using an ethernet to serial device. The communication is facilitated through a small node.js application. The provided code retrieves the necessary information: var net = require('ne ...

Experiencing excessive CPU usage while utilizing a progress bar in Angular

Whenever I try to load a page with 2 progress bars, my CPU usage goes through the roof... I decided to investigate and found that once I removed them, the site's speed improved significantly. Here's a code snippet of one of the progress bars: ...

Creating a JSON document with a specific structure using Java

I am currently working on generating a JSON file using Java in a specific format. To clarify, let's assume that I want the JSON file to be structured like this: { "resource":[{"name":"Node1"}], "literals":[{"literal":"A", "B", "C", "D"}] } Essentia ...

Tips for achieving JSON formatting with JavaScript or jQuery

To achieve the desired output format, I am required to transform the provided input json. input json: [ { "key a": "value alpha" "key b": "value beta" "key c": "value gamma& ...

What is the best way to utilize Link navigation in order to navigate away from a blocked route in the latest version of Next.js,

DISCLAIMER: I raised this issue on the Next.js GitHub repository, but it was closed without recognition. The solution provided did not resolve my problem, leading me to seek help here. The Issue at Hand I have created a demo app (accessible here) on Code ...

JQuery fails to retrieve accurate width measurements

Utilizing this code snippet, I have been able to obtain the width of an element and then set it as its height: $(document).ready(function(){ $(".equal-height").each(function(){ var itemSize = $(this).outerWidth(); cons ...

How to use the ObjC RestKit library for object mapping to a JSON NSString?

I'm currently utilizing RestKit on iOS. I've set up an object and its mapping, allowing me to communicate data with the server. Now, I'd like to have the -description method of my mapped objects return the JSON mapping for easier logging to ...

Designing Object-Oriented JavaScript

Currently, I am in the process of developing a sophisticated JavaScript application. Utilizing an object-oriented design approach, I have organized my code into various files to enhance maintainability. In order to create my application, what is the best ...

Struggling with JavaScript's getElementById function

If anyone has any suggestions or alternative methods, please kindly assist me. I currently have: 1 Textbox 1 Label 1 LinkButton Upon clicking the lnk_NameEdit button, the txtUserName textbox should become visible while the lblusername label should becom ...

The attempt to convert the value from type '__NSSingleObjectArrayI' to 'NSDictionary' was unsuccessful

Having trouble parsing the response from the iTunes lookup API while trying to check the version of my app. Here's the code snippet: static func needsUpdate() -> Bool { do { let infoDictionary = Bundle.main.infoDictionary let a ...

The issue of jQuery's .last() function triggering multiple times with just a single click on the last

I currently have a set of tabs containing radio buttons and I need to trigger an event when the last option is selected (meaning any radio button within the final tab, not just the last radio button). Below is the HTML code: <div id="smartwizard" clas ...

Discover the perfect method for combining two objects while updating any empty values with a new specified value. Furthermore, in the case where the new value is also

My task involves working with an array of objects where each time I select a value, it gets pushed into the array. My goal is to merge two objects that share the same key "code" and remove any empty values. (4) [{…}, {…}, {…}, {…}] 0: {code: "abc ...

Error: 'window not defined' or 'document not defined' encountered while importing a module in Next.js

I'm working on integrating a Wysiwyg editor into my web application. However, I encountered an error when trying to import the editor module. I tried using both react-draft-wysiwyg and react-quill. The former resulted in a "window not defined" error, ...

Ways to retrieve the specified data in Javascript in string format

I'm facing an issue where the data I passed from a JavaScript array to a Java servlet and back to JavaScript is showing as "undefined." Check out my JavaScript code below: var buildingNumbers = []; // Let's assume the values of buildingNumbers ...

Selenium, scrolling through web pages

I have been attempting to scroll through a webpage using Selenium at "https://jobsearch.az/vacancies". However, when you open the page and click on a job vacancy, there are two side-by-side pages that need to be scrolled. The challenge is to scroll the one ...