5

I'm newbie to json. I'm learning more things in Json schema but I stood helpless in testing my user.json file against json-schema.json file. Please note I need to test with a javascript variable which should return either true or false to process further. Hereby I pasted my files.

json-schema.json

{
  "description": "Any validation failures are shown in the right-hand Messages pane.",
  "type": "object",
  "properties": {
    "foo": {
      "type": "number"
    },
    "bar": {
      "type": "string",
      "enum": [
        "a",
        "b",
        "c"
      ]
    }
  }
}

user.json

{
 "foo": 12345,
 "bar": "a"
}

When I tested the above code in http://jsonschemalint.com/#/version/draft-05/markup/json IT say's user.json is in right format. But I need to test locally

Thanks in advance.

Barmar
  • 741,623
  • 53
  • 500
  • 612
anna poorani
  • 690
  • 1
  • 8
  • 17

1 Answers1

4

You can use one of JSON schema validators.

Example of using one of these libraries, ajv:

import Ajv from 'ajv';

import schema from 'schema.json';
import data from 'data.json';

function isValid(schema, data) {
  const ajv = new Ajv();
  const valid = ajv.validate(schema, data);

  if (!valid) {
    console.log(ajv.errors);
    return false;
  }

  return true;
}
quotesBro
  • 6,030
  • 2
  • 31
  • 41