RSKMR RSKMR - 27 days ago 9
Node.js Question

Node + Json format validator

I have few questions in server side.

I have more than 50 API.

Need to check every API (GET,POST) method the following things.


  1. Validate the input is valid json.

  2. Input data need to check the some of the key name with data.



For example 1:

{
"name": "<city name1>",
"status": 1,
"id" : 3,
"code" : 5,
"abcd" : "44",
---------------
------------
}


In this above Input I need to check few key are mantory. eg: name, code

Example 2:

{
"country": [
{
"state": [
{
"name": "<city name1>",
"status": 1
}, {
"name": "<city name2>",
"status": 2
}, {
"name": "<city name3>",
"status": 3
}
],
"name": "<state Name1>"
}, {
"state": [
{
"name": "<city name1>",
"status": 1
}, {
"name": "<city name2>",
"status": 2
}, {
"name": "<city name3>",
"status": 3
}
],
"name": "<state Name2>"
}
]
}


In above example I need to check the state and city > name is mandatory.

I checked the packages but not get suitable one for me.

Have any packages for check the json validation?

Answer

I use validator. It has many functions like isEmail, isAlphaNumeric etc...

It also supports sanitization. Samples and tests in the repo.

To check if key exists, you can use standard hasOwnProperty

Check if a key exists inside a json object

Those options will be fast and offer the ability to craft very specific custom checking and better error messages back to the consumer.

Another option is json schema. Might be faster peformance wise to simply check code (above) but with json schema you could create common code in your api that loads schema files for each api so may lead to less code.

An example lib.

https://www.npmjs.com/package/jsonschema

So, it's a balance of more/less code, performance and how custom you want your checking and error messages to be.