forked from simranlotey/Hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonValidator.ts
37 lines (31 loc) · 896 Bytes
/
jsonValidator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
type Schema = Record<string, string>;
function validateJSONAgainstSchema(json: any, schema: Schema): boolean {
for (const key in schema) {
if (schema.hasOwnProperty(key)) {
const expectedType = schema[key];
const actualType = typeof json[key];
if (actualType !== expectedType) {
console.error(`Validation error for key "${key}": Expected type "${expectedType}", but got "${actualType}".`);
return false;
}
}
}
return true;
}
// Example usage
const jsonToValidate = {
name: "John Doe",
age: 30,
email: "[email protected]",
};
const userSchema: Schema = {
name: "string",
age: "number",
email: "string",
};
const isValid = validateJSONAgainstSchema(jsonToValidate, userSchema);
if (isValid) {
console.log("JSON is valid according to the schema.");
} else {
console.error("JSON is not valid according to the schema.");
}