Geni1
Tera Contributor

http://genipalla.com/servicenow/json-validation-servicenow/

JSON Validation – ServiceNow

JSON validation has been around for many years and there are quite a plethora of different javascript libraries out on git hub that can be used to validate your json payloads within your web apps. It came as a surprise to me that most people on the ServiceNow platform do not use a JSON validation library and instead opt to use a chain of if statements, chained functions, or simply wrap a section of code with a try catch block and call it a day. This can be a simple solution when you are working on an isolated feature, however can turn messy really quickly when you are trying to build a scalable solution. The beautiful part of ServiceNow is that almost every piece of data within the platform is served up in a JSON format and this is where JSON validators really shine.

Resources

TV4

Tiny Validator v4 was actually picked for a couple of different reasons:

  • Small package size
  • Supports an industry standard schema format
  • No modifications required to drop into ServiceNow
  • Can be used in Script Includes
  • Supports Async Validation

First we need to import tv4 into our ServiceNow instance to do this we will create a new script include and literally copy paste the library into the script include code section (yes its as easy as that).
https://github.com/geraintluff/tv4/blob/master/tv4.js <– TV4 code

JSON Schema

The payload we will be working with is as follows:

{
  "checked": false,
  "dimensions": {
    "width": 5,
    "height": 10
  },
  "id": 1,
  "name": "A green door",
  "price": 12.5,
  "tags": [
    "home",
    "green"
  ]
}

So in this payload all we care about is the id, price and tags. We will use the Generator tool to produce our schema

The schema that is generated is pretty straight forward

At the top layer we have a required key that tracks all required fields then each property has and $id, type, title and pattern which can be modified to meet your validation needs.

Generator Tool: https://jsonschema.net/

{
  "definitions": {},
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "http://example.com/example.json",
  "type": "object",
  "title": "The Root Schema",
  "required": [
    "id",
    "price",
    "tags"
  ],
  "properties": {
    "checked": {
      "$id": "/properties/checked",
      "type": "boolean",
      "title": "The Checked Schema",
      "default": false,
      "examples": [
        false
      ]
    },
    "dimensions": {
      "$id": "/properties/dimensions",
      "type": "object",
      "title": "The Dimensions Schema",
      "required": [
        "width",
        "height"
      ],
      "properties": {
        "width": {
          "$id": "/properties/dimensions/properties/width",
          "type": "integer",
          "title": "The Width Schema",
          "default": 0,
          "examples": [
            5
          ]
        },
        "height": {
          "$id": "/properties/dimensions/properties/height",
          "type": "integer",
          "title": "The Height Schema",
          "default": 0,
          "examples": [
            10
          ]
        }
      }
    },
    "id": {
      "$id": "/properties/id",
      "type": "integer",
      "title": "The Id Schema",
      "default": 0,
      "examples": [
        1
      ]
    },
    "name": {
      "$id": "/properties/name",
      "type": "string",
      "title": "The Name Schema",
      "default": "",
      "examples": [
        "A green door"
      ],
      "pattern": "^(.*)$"
    },
    "price": {
      "$id": "/properties/price",
      "type": "number",
      "title": "The Price Schema",
      "default": 0.0,
      "examples": [
        12.5
      ]
    },
    "tags": {
      "$id": "/properties/tags",
      "type": "array",
      "title": "The Tags Schema",
      "items": {
        "$id": "/properties/tags/items",
        "type": "string",
        "title": "The 0 Schema",
        "default": "",
        "examples": [
          "home",
          "green"
        ],
        "pattern": "^(.*)$"
      }
    }
  }
}

We will now take this JSON schema and save it in a new script include as a variable that is return when our function is called.

Validating a payload

Now to validate a payload take the following script as an example

var tv4 = new global.tv4();
var schemas = new global.schemas();

var payload = {
  "checked": false,
  "dimensions": {
    "width": 5,
    "height": 10
  },
  "id": 1,
  "name": "A green door",
  "price": 12.5
};

var result = tv4.validateMultiple(payload, schema.getDemoSchema());

The result will show that our payload is invalid because the tags array is missing.

{
    "valid": false,
    "errors": [
        {...},
        ...
    ],
    "missing": [...]
}
Comments
Dan120
Kilo Explorer

Hi, Thanks for the article. It is really helpful. I am trying it out and facing the first step: 

First we need to import tv4 into our ServiceNow instance to do this we will create a new script include and literally copy paste the library into the script include code section (yes its as easy as that)

 

In my case, we use different application scope other than global. I could not get it working here, keep getting:

Evaluator: org.mozilla.javascript.EcmaError: <<application name>> is not a function.
   Caused by error in script at line 18
Evaluator: org.mozilla.javascript.EcmaError:
<<application name>>
is not a function. Caused by error in script at line 9
Evaluator: org.mozilla.javascript.EcmaError:
<<application name>>
is not a function. Caused by error in script at line 1


Any help is very much appreciated.

Thx
muthuramachandr
ServiceNow Employee
ServiceNow Employee

Hi Dan

Are you able to resolve the issue. I'm facing the same issue.

JagjeetSingh
Kilo Sage
Kilo Sage

I see many folks having issues using the tv4 library. I also did face issues stated above.

Use attached script include XML.

 

Edit: Looks like attachment is not supported now with comment.

Please find the xml file at jdsingh206/tv4SchemaValidator: Update set XML to validate JSON schema in ServiceNow (github.com)

catwood
Tera Contributor

hmmm, I pulled this into my San Diego PDI and attempted to call as described in the article. Still getting the "is not a function) error when trying to run it. 

catwood
Tera Contributor

ok - got it working. You have to call it differently as the script include is not a class. So, something like this:

var tv4 = tv4.validateMultiple(payload, getSchema());
Jonathan Murill
Tera Contributor

@JagjeetSingh There is nothin attached in your comment, can you please re-attach the XML Script Include?

@catwood I'm facing the same issue you commented before, I really don't know that if when crating the Script include you imported the code inside the server side initialization part of the code:

JonathanMurill_0-1668208218840.png

Or if the code should be Client Callable. If anything I'm very interested in knowing, how you make this work?

I really need help with this, I'll appreciate any response.



JagjeetSingh
Kilo Sage
Kilo Sage

@Jonathan Murill , I've updated my comment. Please check now.

YaronN
ServiceNow Employee
ServiceNow Employee

 

JagjeetSingh,
Works great.
Thanks.
Version history
Last update:
‎01-27-2020 06:36 AM
Updated by: