In: Computer Science
Write a javascript code to check if the JSON body follows the schema.
schema is
{
"name":"john doe",
"mood":"happy"
"major":"cs",
"date":"2024"
}
json body is
{
"name":"john doe",
"height":"170cm"
"major":"cs",
"date":"2024"
} the result should be false
Hey there ,
I've added code below to check json body for the example given by you. please find the code below . if you find any difficulty or face any issue please comment down or try to connect with me.
Approach 1:
var SchemaToBeChecked = {
"name": "john doe",
"mood": "happy",
"major": "cs",
"date": "2024"
};
var JsonBody = {
"name": "john doe",
"height":"170cm",
"major": "cs",
"date": "2024"
};
var flag = JSON.stringify(SchemaToBeChecked) === JSON.stringify(JsonBody);
console.log(flag)
Output:
Approach 2:
1. In this approach you need to use lodesh Module which provide _isEqual (json1 , json2) method which will check the schema.
Example Code for that is given below.
_.isEqual(one, two); // true or false
Approach 3:
Check only keys:
var JsonBody = {
"name": "john doe",
"mood":"sad",
"major": "cs",
"date": "2024" };
var SchemaToBeChecked = {
"name": "john doe",
"mood": "happy",
"major": "cs",
"date": "2024" };
keyObj1 = Object.keys(SchemaToBeChecked);
keyObj2 = Object.keys(JsonBody);
let flag = false;
// now compare their keys
if (keyObj1.length == keyObj2.length) {
for (var i = 0; i < keyObj1.length; i++) {
if (keyObj1[i] == keyObj2[i]) {
flag = true;
} else {
flag = false;
break;
}
}
}
console.log(flag)
Output :