Create JSON instance from JSON schema

Viewed 1541

Hi I'm trying to create JSON instance from a JSON schema.

Typescript answer is appreciated, but appreciate any answers.

Below the the sample-schema.json file. I want to create a function to convert a schema to a schema instance.

Ex: sample-schema.json

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string"
    },
    "last_name": {
      "type": "string"
    },
    "address": {
      "type": "object",
      "properties": {
        "street_1": {
          "type": "string"
        },
        "street_2": {
          "type": "string"
        },
        "city": {
          "type": "string"
        },
        "state": {
          "type": "string",
          "enum": [
            "AL",
            "AK",
            "AS"
          ]
        },
        "zip_code": {
          "type": "string"
        }
      }
    },
    "birthday": {
      "type": "string"
    },
    "notes": {
      "type": "string"
    }
  },
  "required": [
    "last_name"
  ]
}

Desired output:

{
  "first_name": "",
  "last_name": "",
  "last_name": "",
  "address": {
    "street_1": "",
    "street_2": "",
    "city": "",
    "state": "",
    "zip_code": ""
  },
  "birthday": "",
  "notes": ""
}

On calling the function, by passing the schema it has to generate the JSON instance. I searched on Google but all the results are from JSON to JSON schema.

2 Answers

fetch the value of the sampleSchema and use the javascript JSON.parse(sampleSchema) method.

Related