Is it possible to mark a number surrounded by quotes as invalid in a JSON validation?

I am working with a JSON body that includes various types of values such as numbers, strings, Booleans, and arrays.

{
    "name": "vivek",
    "age": 12,
    "employed": true,
    "cars": ["maruti", "wagonR"]
}

When it comes to the age value, only {"age":12} is considered acceptable. If any other format is entered, the system should prompt for the age to be re-entered (e.g. {"age":"12"}). What are some possible ways to validate this requirement?

Answer №1

To ensure the validity of the JSON data, it is important to parse it and verify the type of the property 'age'. There are additional methods that can be used, but checking the type is more secure as the age property can vary in value. Attempting to access the constructor property directly may lead to unexpected errors.

var jsonData = JSON.parse('JSON DATA GOES HERE');

// Quickly validate if operations on 'jsonData' getters can take place
if (jsonData) {
    var personAge = jsonData.age;

    if (jsonData.hasOwnProperty('age')) {
        var dataType = typeof personAge;
        if (dataType !== 'number')
            throw new Error('The age property must be a number, not a ' + dataType);
    } else {
        throw new Error('The age property is missing in the JSON data');
    }
}

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

Leveraging Angular, ExpressJS, and NodeJS to enable users to download a text file by simply clicking a

My goal is to incorporate a download button that allows users to download a document from my node.js server. Behold the stylish download button: https://i.sstatic.net/s4CjS.png My tech stack includes Angular for the front-end and node.js along with exp ...

React triggering onClick event before user clicks

Is there a way to delete the li element when the user clicks on the delete button? I tried passing the index but it seems to trigger before I click on it. Maybe I am not handling the value correctly. http://jsfiddle.net/axhpuepq var App = React.createCla ...

I want to customize my Google Apps Script to only target specific cells, not all cells

I need help with a script that changes the currency symbol within specific cells based on user selection. Currently, the script is applied to all cells but I only want it to affect cells C9, C12, and C13. I'm not sure where to make this adjustment in ...

What is the best way to reveal a hidden div using JavaScript after a form submission?

jQuery is not a language I am very familiar with, but I am attempting to display a simple animated gif when a form is submitted. When users click 'submit' to upload an image, I want the gif to show to indicate that the image is being uploaded. Th ...

What is the best way to ensure a function returning a promise works effectively within a forEach loop?

Are you facing challenges using a function that returns a promise inside a forEach loop due to the asynchronous nature of the function? It seems like the forEach loop completes before the promise can finish fetching or manipulating the data. Below is a co ...

I encountered an issue while operating my next.js application which utilizes solidity smart contracts. The error message "Cannot read properties of undefined" was displayed during the process

While working on my next.js app and attempting to fetch user data, I encountered the "cannot read properties of undefined" error. https://i.stack.imgur.com/SBPBf.png I also received the following error in the console https://i.stack.imgur.com/JBtbO.png ...

What is the best approach for sending mapbox coordinates to a higher-level class in a react application?

As a beginner in learning React, I'm currently working on setting a map marker with a click event on a Mapbox GL map. The challenge I'm facing is passing the lngLat object back up to the parent component. Can someone guide me on how to achieve th ...

Accessing JSON data and populating a dropdown menu with JQuery

I am facing an issue with extracting values from a JSON array using jQuery. The structure of the array is as follows: [{ "": "Select your State/Region" }, { "BAL": "Balkh" }, { "BAM": "Bamian" }] Although I have attempted to loop through the array in ord ...

Tips for including attributes in form input HTML tags

Is there a way to modify an attribute of an HTML element? I attempted the following code snippet, but the attribute does not seem to be updating as expected. $(document).ready(function() { $('#username_input').attr('value', 'som ...

Steps to create a clickable image input

How can I make an image clickable in an input with type=file? <label for="formFileSm" class="label_display form-label">avatar</label> <input class="width_input mx-auto form-control form-control-sm" id="fo ...

Error EPERM: Attempting to delete forbidden operation on 'C:Users** ode_modules.node-sass.DELETEvendorwin32-x64-57inding.node'

I encountered an error when trying to execute "npm install". OS: Windows 10 npm: 6.2.0 node: v10.9.0 Despite attempting to run "npm install" following the command "npm cache verify", the issue persists. npm cache verify npm instal Upon running th ...

Change the keys of the object in the return statement

Scenario Imagine a scenario where a method called matter is returning an object in the form of return {content, data} Issue There is a conflict when the method is called a second time, as it overwrites any previous variables that were set from the return ...

Sails.js seems to be malfunctioning, as it does not seem to be recognizing the term 'sails'

It seems like I'm encountering an issue with the 'sails' command not being recognized on my Windows 10 system. Despite following all the installation steps, including globally installing Sails.js through npm and ensuring Node is installed, I ...

Implementing HTML in MVC using MvcHtmlString.Create while incorporating JavaScript features

I am facing a major dilemma. In my MVC project, I am rendering an HTML template (loaded from a .html file) into a View using MvcHtmlString.Create(); While this method works fine, there is a problem that arises. The HTML template requires JavaScript functi ...

Retrieving information from a JSON array in a MariaDB database

I need help retrieving records from an array where the end date is earlier than today's date and the id is 14. Despite trying, I am unable to get any results. How can I successfully retrieve these records? CREATE TABLE `test_udc` ( `id` int(10) NOT ...

Tips on swapping out an image multiple times as you hover over various text options

As a Designer creating a portfolio website, I have a good understanding of HTML and CSS. Here is my homepage: https://i.sstatic.net/WWMPA.png I am looking to create a feature where different images are displayed in a red circle preview when hovering over ...

Learning how to track mouse wheel scrolling using jQuery

Is there a way to track mouse scrolling using jquery or javascript? I want the initial value to be 0 and increment by 1 when scrolling down and decrement by 1 when scrolling up. The value should always be positive. For example, if I scroll down twice, the ...

Function that returns an array

Hey there, wondering about variable scope in closures! I've come across a lot of questions on this topic but haven't found the solution to my issue. Here's the code snippet: var teams = []; var players = []; var getRoles = function(roleL ...

Error encountered while scrolling with a fixed position

I am currently in the process of developing a carousel slider that resembles what we see on Android devices. The main challenge I am facing at this early stage is applying the CSS property position: fixed; only horizontally, as vertical scrolling will be n ...

Why does my POST request result in [object Object] being returned?

I am just starting to learn AngularJS and I am unsure if my POST request is functioning correctly. After making the request, I am receiving an [object Object] response. What does this error indicate? Could it be related to an issue with the form? //Acti ...