Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to default construct JavaScript object from JSON Schema?

I've started using Newtonsoft.Json.Schema.JsonSchemaGenerator along with various property attributes over in my C# code to help keep my client script DRY. What I'd like to do is create a default initialized object client-side based on the schema from the server. This would be useful for, say, when the user clicks 'New Foo' to add a new entry into a table.

Obviously I can just code it up to iterate the .Properties and build up the new object, which is what I'm doing at the moment. However I'd prefer to avoid reinventing any wheels.

Are there any JS libraries for working with JSON schema that will do this, among other nifty things I've yet to realize I need?


1/29/2013 UPDATE

Some people have attempted to answer my question and have been off base, and as a result have received some negative feedback from the SO community. So let me attempt to clarify things. Here is the challenge:

  • In JS client script, you have an object that represents the JSON Schema of another object. Let's say, this came from the server via JSON.NET and is the representation of a C# class.

  • Now, in the JS client script, create one of these objects based upon the JSON Schema. Each field/property in the object must be default initialized according to the schema, including all contained objects!

  • BONUS: Bind this new object to the UI using MVVM (eg Knockout). Change some of the fields in response to user input.

  • Send this new object to the server. The server-side code will add it to a collection, database table, whatever. (Yes, the object will be sent as JSON using Ajax -- we can assume that)

  • No duplication! The only place where the class is defined is in the server-side code (C# in my example). This includes all metadata such as default values, description text, valid ranges, etc.

like image 585
BrandonLWhite Avatar asked Oct 01 '12 17:10

BrandonLWhite


People also ask

How do you turn JSON format a JavaScript object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.

Which method should you use to convert JSON into JavaScript object?

JSON text/object can be converted into Javascript object using the function JSON. parse().

Is every JavaScript object JSON?

The answer is "no". There are cases when JSON object won't be valid for JavaScript. JSON is NOT a JavaScript subset.

Is JSON same as JavaScript object?

Just like XML and YAML is a way to pass structured information between languages, JSON is the same. A JavaScript object on the other hand is a physical type. Just like a PHP array, a C++ class/ struct, a JavaScript object is a type internal to JavaScript.


1 Answers

Yes there is (I tried it with NodeJS):

JSON Schema defaults

Link updated.

like image 89
damorin Avatar answered Oct 24 '22 07:10

damorin