Mapping JSON schema to typed JavaScript objects

Are there any tools available to generate JavaScript typed objects (JS functions) from a JSON schema? Essentially, looking for the JS equivalent of this http://code.google.com/p/jsonschema2pojo/. Thank you.

EDIT:

Starting with:

{
    "description": "An entity",
    "type":"object",
    "properties": {
        "geometries": {"type": "array",
            "items": {
                "$ref" : "geometry"
             }
          }
    }
}

I would like code similar to this to be automatically generated:

function Entity {
    this.geometries;
}

The schema may become more complex with $refs, but I hope this demonstrates the concept.

Answer №1

Have you explored the capabilities of the djvi library for your needs?

The demonstration provided includes:

var jsonSchema = {"common":{"properties":{"type":{"enum":["common"]}},"required":["type"]}};

var env = new djvi();
env.addSchema('test', jsonSchema);
env.instance('test#/common');
// => { type: 'common' }

This could potentially be the solution you are seeking.

If this specific solution is not what you're looking for, I encountered a similar issue and devised a different approach to generate a parent object as a function. It might offer some assistance:

var dbdict = {
    "title": "Entity",
    "description": "An entity",
    "type":"object",
    "properties": {
        "geometries": {"type": "array",
            "items": {
                "$ref" : "geometry"
             }
          }
    }
}

var walkJSONSchema = function (JSONSchema, returnFunction) {

    var walkObject = function(PROPS) {
        var $this = this,
            $child = {}
        ;

        if(returnFunction == true) {
            $child = new function() {};
        }

        //console.log("PROPS");
        //console.log(PROPS);

        for(var key in PROPS) {
            console.log("key:"+key+" type:"+PROPS[key].type+" default:"+PROPS[key].default);
            switch(PROPS[key].type) {
                case "boolean":
                    $child[key] = PROPS[key].default || undefined;
                    break;
                case "integer":
                case "number":
                    $child[key] = PROPS[key].default || undefined;
                    break;
                case "array":
                    $child[key] = [].push($this.walkObject(PROPS[key].properties));
                    break;
                case "object":
                    $child[key] = $this.walkObject(PROPS[key].properties);
                    break;
                case "string":
                    $child[key] = PROPS[key].default || undefined;
                    break;
            };
        };

        return $child;
    }

    return walkObject(JSONSchema.properties);
}

Entity = walkJSONSchema(dbdict, true);

You have the flexibility to customize how you access the "Entity" from the schema document using your preferred scripting method, but this provides a functional option.

Answer №2

It seems like you'll need to tackle that problem solo. Regardless, the process shouldn't pose too many challenges. Simply parse through the JSON data available to you and then loop through each element, implementing the desired logic for each "class" before adding the outcome to a string. Upon completion, display the string and utilize a JS formatter to perfect your code.

Answer №3

If you're looking to differentiate your JSON objects, consider adding a unique "_type_" property to each one (choose a quirky name to avoid conflicts) to indicate their type. Then, in JavaScript, you can map this string to another object that specifies the available properties.

While this approach is possible, it may not necessarily be the best practice as JSON is typically designed for direct usage in JavaScript.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing Array Data in Angular $scope (Javascript)

I am currently altering the Altair Material Design Template and incorporating an Angular JS controller. After successfully calling an API and creating variables in a for loop, I intend to write them to $scope.dragulaItems. While this process seems to work ...

Issue with managing timezones in Angular with CDT/CST offsets

I have a date in UTC format that I need to convert to CST. It is 5 hours ahead of UTC during CDT and 6 hours ahead during CTC. The UTC date is '2016-09-07T05:00:00Z' <body> <div ng-app="myApp" ng-controller="datCtrl"> <p>Da ...

Decode the implicit list in JSON format provided by the keys "1" and "2"

After retrieving this JSON data from an API, I need to convert it into a Java object. Here is the JSON structure: { "message" : "message", "1": { "packageCode": "packageCode1", " ...

I am working on a NodeJs code that utilizes (Array)Buffers and native readUInt16BE. However, since I am working within a browser context, I plan to opt for DataView.getUint16 instead

While working on adapting a JPEG parsing function in Node.js for use in a browser environment, I discovered that the original code can be found here. The challenge lies in using Node.js' Buffer class. To make it compatible with a browser environment, ...

Tips for checking the type radio button input with Angular.js

I want to implement validation for a radio button field using Angular.js. Below is the code snippet I am working with: <form name="myForm" enctype="multipart/form-data" novalidate> <div> <input type="radio" ng-model="new" value="true" ng- ...

The concept of overloading operators in V8

Here's a question that I've been pondering, but couldn't seem to find any answers for on Google. While it may not be achievable in pure JavaScript, let's say I'm developing a container class in V8 and then returning that class bac ...

Tips on preventing unexpected growth of rect width or height when snapping in Konva

While trying to resize a rectangle in order to make it into a perfect square, I encountered an issue where the height or width of the rectangle would unexpectedly grow. This can be seen in the GIF below: You can view the codesandbox link here: https://cod ...

The issue of the "port" attribute not working for remotePatterns in the Image component has been identified in Next.js 13's next.config.js

I've encountered an issue with the code snippet below. I'm attempting to utilize remotePatterns in my next.config.js file to enable external images. Strangely, when I set the port to an empty string "", it functions correctly. However, specifying ...

Unable to modify background color in base website

While working on my project with Next.js, I encountered an issue where creating a button to change the color only affected the base web components' color and not the background color. _app.tsx import '../styles/globals.css'; import type { Ap ...

Export generated JSON as a file in Node.js

My server is creating a JSON object/array and I want to send it to the user as a file, not displayed on the browser. How can I achieve this? I'm hesitant about writing it to a file and then utilizing res.sendFile(). Is there a better way to handle th ...

Introducing the First Angular Factory

It's high time for me to finally inject my first angular Factory . . . Here is the code I have: .factory('Debts', function($q, $scope){ return MA; }) .controller('Admin', function ($scope, Debts) { $scope.Debts = Deb ...

Using Vuex's v-model to bind to a state field in an object

In my current Vuex state, I have defined a getter named configs, which looks like this: configs: { 1303401: { exampleValue: 'test' } } There is also an input where I bind the exampleValue from the Vuex store's state using v-mo ...

Trigger a function upon the initial keypress event detected on an input field

I am facing an issue with an input element that has an onkeypress event triggering a function called change(). Strangely, the function does not execute on the very first keypress. I notice that I have to input 55 instead of just 5 for the function to updat ...

Generating a hierarchical JSON structure using Pandas for an organizational chart

I am working on transforming a hierarchical DataFrame in Python 3.5 into a nested JSON object for use in JavaScript to display an Org Chart. I am aiming to achieve the structure outlined in the response provided in this question: Organization chart - tree, ...

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Mapping YAML file to a Java Map without using a custom deserializer

I have a YAML file that I want to load into a Map instance without having to define a custom deserializer. Is there a way to achieve this using annotations or any other method? Below is an example of the YAML file: - site: First Site url: some_url us ...

Loading of iframes occurs only after receiving the content sent through the postMessage function

I have a scenario where an iframe is used to receive information through the contentWindow.postMessage function in order to log in to a page that I am creating. However, I am facing an issue where the page loads before the contentWindow.postMessage message ...

Listener of events calculates the outcome

In need of help with retrieving the current coordinates of a clicked point on Google Maps. Here is my code snippet: let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); getCoords() { google.maps.event.addListener ...

Comparing the Length of JavaScript Arrays

I have code that checks for similar values in two arrays, and if there are any, they are not displayed in the result. However, when I switch the lengths of the arrays so that Array2 is longer than Array1, I end up with an empty result array. How can I achi ...

Creating a pie chart with ExtJS using data from a JSON file

After successfully creating a pie chart using ExtJS with JSON values through AJAX calling, I encountered an issue when trying to do the same with JSON values retrieved from a file named myjson.json. Can anyone advise me on how to draw a pie chart by retrie ...