Validation of JSON array items

I am in need of a tool that can validate JSON data with specific examples. Here is the JSON fragment:

{
    "optionsMinValue": 0
    "optionsMaxValue": 56
    "options": [
        {
            "name": "name1",
            "value": 0
        },
        {
            "name": "name2",
            "value": 1
        },
        {
            "name": "name3",
            "value": 56
        }
  ]
}

Specific validation cases:

  • When analyzing the above fragment, the validation for optionsMaxValue must pass.

  • If the optionsMaxValue is altered to 55 in the given fragment, then the validation should return an error.

Bonus validation criterion:

  • There must be an item in the options array for every whole number between optionsMinValue and optionsMaxValue. In this case, there should be 57 items in the array corresponding to values from 0 to 56.

Current tools available:

Are there any tools readily available to efficiently carry out these validations?

Initially, I thought about utilizing json-schema validation. However, it has been quite some time since I explored that option, so I am hopeful that more advanced tools have been developed for this purpose.

Answer №1

Ajv JSON schema validator - click here for the GitHub link

const schema = {
  type: "object",
  properties: {
    name: {type: "string"},
    value: {type: "number", minimum: 0, maximum: 55},
  },
  required: ["name", "value"],
  additionalProperties: false,
}

const option = {
    "name": "exampleName",
    "value": 10
},

const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ajv/4.4.0/ajv.min.js"></script>

Answer №2

Utilizing the Joi package is highly recommended for conducting these specific validations.

The following Joi schema can be applied to address your particular requirements:

Joi.object({
  optionsMinValue: Joi.number().min(0).max(30).required(),

  optionsMaxValue: Joi.number().min(56).max(100).required(),

  options: Joi.array().items(
    Joi.object({
      name: Joi.string().required(),
      value: Joi.number().min(0).max(56).required(),
    })
  ),
});

Here is a code snippet that effectively addresses your use case:

const inputData = {
  optionsMinValue: 0,
  optionsMaxValue: 56,
  options: [
    {
      name: "name1",
      value: 0,
    },
    {
      name: "name2",
      value: 1,
    },
    {
      name: "name3",
      value: 56,
    },
  ],
};

const Joi = joi; // for node.js use - const Joi = require("joi");

// Schema for validation
const schema = Joi.object({
  optionsMinValue: Joi.number().min(0).max(30).required(),

  optionsMaxValue: Joi.number().min(56).max(100).required(),

  options: Joi.array().items(
    Joi.object({
      name: Joi.string().required(),
      value: Joi.number().min(0).max(56).required(),
    })
  ),
});

const runValidation = (schema, inputData) => {
  const validationResult = Joi.compile(schema)
    .prefs({ errors: { label: "key" }, abortEarly: false })
    .validate(inputData);

  if (validationResult.error) {
    // Validation failed
    console.log("Error, validation failed");
    // Set error message to string
    const errorMessage = validationResult.error.details
      .map((details) => details.message)
      .join(", ");
    console.log("failure reason - ", errorMessage);
    return;
  }
  console.log("validation passed");
};
runValidation(schema, inputData);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="452f2a2c0574726b736b75">[email protected]</a>/dist/joi-browser.min.js"></script>

Answer №3

It is crucial to establish validation rules for any tool you utilize, even if it's a preexisting one. Given that expertise in these tools may vary, writing custom code in your preferred language could simplify the process. For instance, a JavaScript snippet can effectively handle this task:

function validateJson(jsonToValidate, maxValue = 56) {
  if (jsonToValidate.optionsMaxValue !== maxValue) {
    console.log("Failure on optionsMaxValue.");
    return false;
  }
  if (jsonToValidate.options.length !== maxValue+1) {
    console.log("Incorrect number of items.");
    return false;
  }
  let values = jsonToValidate.options.map(a => a.value).sort();
  if (values[0] !== 0 || values[maxValue] !== maxValue) {
    console.log("Values out of desired sequence.");
    return false;
  }
  let sum = values.reduce((a, b) => a + b, 0);
  if (sum !== maxValue * (maxValue + 1) / 2) {
    console.log("Values out of desired sequence.");
    return false;
  }
  console.log("Validation PASSED.");
  return true;
}

Let's consider an example with a truncated JSON object:

let jsonSample = {
  "optionsMinValue": 0,
  "optionsMaxValue": 2,
  "options": [{
      "name": "name1",
      "value": 0
    },
    {
      "name": "name2",
      "value": 1
    },
    {
      "name": "name3",
      "value": 2
    }
  ]
};

function validateJson(jsonToValidate, maxValue = 56) {
  if (jsonToValidate.optionsMaxValue !== maxValue) {
    console.log("Failure on optionsMaxValue.");
    return false;
  }
  if (jsonToValidate.options.length !== maxValue+1) {
    console.log("Incorrect number of items.");
    return false;
  }
  let values = jsonToValidate.options.map(a => a.value).sort();
  if (values[0] !== 0 || values[maxValue] !== maxValue) {
    console.log("Values out of desired sequence.");
    return false;
  }
  let sum = values.reduce((a, b) => a + b, 0);
  if (sum !== maxValue * (maxValue + 1) / 2) {
    console.log("Values out of desired sequence.");
    return false;
  }
  console.log("Validation PASSED.");
  return true;
}

validateJson(jsonSample, 2);

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

Retrieve the value from a checkbox using Flask and then transfer the extracted data to a different template

I am currently working with Weasyprint to showcase some Jinja templates within a Flask Web App. Here is the JSON data I am using: value=["1","2","3","4"] My goal is to pass the 'value' variable to another Jinja template within an if statement. ...

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

The benefits of using a list in JSON

In October, I developed a JSON compiler and decompiler. After extensive testing against various other JSON formats, I was confident in its functionality and moved forward. My main focus was on the compiler, as understanding the variables users throw at you ...

Tips for showing the parsed JSON data in a TableView using a TextField

Hello there, I am just starting out with iPhone development and need some guidance. I'm currently working on incorporating a webservice to fetch JSON response strings, parsing them using JSONvalue and displaying the parsed data on labels through butt ...

Error: NativeScript has encountered difficulty locating the module "@nativescript/schematics"

While attempting to generate a component called "movies" with the command tns generate component movies, I encountered the following error in the terminal log: Could not find module "@nativescript/schematics". I followed the suggestions provided in this G ...

Using @GET parameters with Android's retrofit

I have created an interface to fetch weather data from the OpenWeather API for the city of RZESZOW in the country POLAND. How can I pass query parameters for the user to input their desired city name and country in order to get the weather data? public in ...

Extract JSON elements from a massive document

Looking for a way to update a JSON file in C# by deleting specific data sets? Check out this example below: [ { "ID": "ID0000001", "Name": "ABCD", "Std": "4" }, { "ID": "ID5335355", "Name": "JKLM", "Std": "6" }, { "ID": "ID5353 ...

Differences between JSON.stringify and serialization methods

Does JSON.stringify( ) fully represent the process of serialization, or is it simply a component of the serialization process? In simpler terms, is JSON.stringify( ) all that's required for serialization, or does it fall short? Is it essential but no ...

Converting JSON formats with Python module: A step-by-step guide

Is there a way to use a Python module to convert one JSON format to another? I have a JSON object and need to extract the keys and values. How can this be accomplished? Thank you in advance. Input json: { "A": { "sensitive": false, "type": " ...

Executing a CRM javascript button triggers a request to a JSON URL and extracts a specific value

My current task involves creating a button in JavaScript due to system limitations preventing the use of HTML. This button should navigate to a specific URL (REST API to retrieve a JSON file). Furthermore, upon clicking the button, I aim to display an aler ...

Utilizing CakePHP 3.0 with jQuery UI for an autocomplete feature

Seeking assistance on why the current code isn't functioning. The objective is to retrieve data from the index controller to search and obtain JSON data. No requests are being made, and there are no visible results. New to CakePHP 3.0, I am attemptin ...

Mapping an array of strings to model field values in EXTJS

I currently work with EXT JS 4.1.1. Upon receiving a JSON response structured as follows: { values: ["A","B","C"] } I proceed to define a model in the following manner: Ext4.define('model', { extends: 'Ext4.data.model', fiel ...

Tips for building a versatile fetch function that can be reused for various JSON formats within a React application

Using the fetch method in various components: fetch(url) .then(result => { if (!result.ok) { throw new Error("HTTP error " + result.status) } return result.json() }) .then(result => { ...

List view encountered a null object reference

I am currently working on a listview in a fragment where I am populating it with information sourced from a JSON call. I seem to be encountering an issue while setting up the listview in my fragment. Since my fragment only extends Fragment, I suspect this ...

Imagine a scenario where your json_encode function returns API data that is already in JSON format. What would

It has been a while since I last worked with JSON/PHP/AJAX, and now I am struggling to access the returned data. The AJAX function calls a PHP script that makes an API call returning JSON in $data. The JSON is then decoded using $newJSON = json_decode($da ...

guide for interpreting a complex json structure

I'm attempting to extract data from a JSON file that has multiple layers, like the example below. - "petOwner": { "name":"John", "age":31, "pets":[ { "animal":"dog", "name":"Fido" }, ...

Is there a solution to address the error message: json.decoder.JSONDecodeError: Expecting value at line 1, column 1 (character 0)?

I am currently working on developing a REST API that involves handling JSON files. One particular aspect of the project requires me to open a JSON file, check for specific content existence, and add it if necessary. To achieve this, I need to load the JSON ...

Unable to convert the text string into my desired object

The JSON string I received has been validated by jsonlint. A decodedCookie string is created using URLDecoder to decode the value of myCookie in UTF-8 format, and then Gson is used to parse it. Here is what the string looks like: { "urlAW": "http://w ...

Error encountered while making an http get request for a node that returns JSON

I've been struggling with this issue for quite some time now. While I've come across similar problems on Stack Overflow, none of the suggested solutions seem to work for me. I keep encountering the following error message: undefined:1 SyntaxErro ...

Using Angular to Apply a Custom Validation Condition on a FormGroup Nested Within Another FormGroup

I am facing an issue with my form validation logic. I have a set of checkboxes that need to be validated only when a specific value is selected from a dropdown. The current validator checks the checkboxes regardless of the dropdown value. Here's the c ...