Home > Enterprise >  Convert a javascript object to json schema
Convert a javascript object to json schema

Time:10-15

I'm totally new to Javascript so please bear with. I want to convert a Javascript object to Schema. It could be done easily with a json string but json can't include function. Therefore i want to ask how a JS object can be converted to Schema. One way i got to know was through npm and nodejs but i couldn't understand it. Here is the link npmjs.com/package/to-json-schema

I have this Javascript object

const Cost = {
    Source: "abc",
    Unique: "abc_001_ccode1",
    Code: "abc_001",
    CodeName: "ccode1",
    Description: "Description1",
    Active: true,
    count: function() {
    Object.keys(Cost).length;
      } 
 }

What i would like is that i can convert this object to Json Schema and the function should give the length of the object(number of attributes) in the properties of Cost object apart from the individual properties of the attribute. Like this

"definitions": {},
"$schema": "http://json-schema.org/draft-07/schema#", 
"$id": "https://example.com/object1634208659.json", 
"title": "Root", 
"type": "object",
"required": [
    "Source",
    "Unique",
    "Code",
    "CodeName",
    "Description",
    "Active"
],

It should contain the length as a property of the Cost Object.

Shall be really helpful if you could also give an example of this implementation for better understanding.

CodePudding user response:

You cannot use JSON schema for an object that contains a function() - if stringify cannot handle the function the schema cannot either.

This link converts

{
    Source: "abc",
    Unique: "abc_001_ccode1",
    Code: "abc_001",
    CodeName: "ccode1",
    Description: "Description1",
    Active: true,
    count: "not a function"
 }

to

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "Source": {
      "type": "string"
    },
    "Unique": {
      "type": "string"
    },
    "Code": {
      "type": "string"
    },
    "CodeName": {
      "type": "string"
    },
    "Description": {
      "type": "string"
    },
    "Active": {
      "type": "boolean"
    },
    "count": {
      "type": "string"
    }
  },
  "required": [
    "Source",
    "Unique",
    "Code",
    "CodeName",
    "Description",
    "Active",
    "count"
  ]
}
  • Related