Explain the concept of parameter JSON or object

I have a method that currently draws some controls on the screen. Now, I want to turn this method into an API in order to make it more dynamic for the user to decide which controls they want to draw. I was thinking of using a JSON structure, but I'm not sure if that would be better than using objects. Any suggestions?

For example:

withSection1 true
withSection2 false
withSecttion3 false
withSection4 true
.....

But I also want to provide a default option for the user to draw all controls without having to specify each section individually. I'm not sure how to implement this.

Update:

If I use a JSON format for the sections, how should I include the default setting in the method signature if the user wants to draw all controls by default?

{
    "withSection1": 'true'
    "withSection2": 'true'
    "withSection3": 'false'
    "withSection4": 'true'

}

Therefore, the method signature would look like drawScreen(jsonStr)

Answer №1

One significant distinction between using simple objects and JSON data is the inability to include functions within JSON structures.

If your application does not require functions at all, opting for JSON can be advantageous as it offers more constraints. This limitation helps prevent users from executing unwanted actions and also facilitates interoperability with other programming languages.

Nevertheless, in my javascript/node.js framework (accessible via a link in my profile), I leverage javascript objects extensively for configuration purposes. The object-oriented approach proves to be more modular, enabling code factorization, file merging with minimal effort, and slight performance enhancements during interpretation. It's worth noting that JSON does not support comments.

Here are simplified examples illustrating the use of objects and JSON:

Object

// foo.js
var foo = {
    foo: 1
};

// bar.js
var bar = {
    bar: function() { return 2; }
};

// merge.js
var obj = merge(foo, bar); // Implement merge function just once.

JSON

foo.json (no comments)

{
    "foo": 1
}

bar.json (no comments)

{
    "bar": 'no functions'
}

// merge.js
// Retrieve the JSON files, parse them (use JSON.parse in javascript), and then merge them.

To explore advanced utilization of objects, please refer to the linked resource in my profile.

UPDATE

If you wish to define default values and specify fields and their types within your JSON structure, consider creating another JSON or an object outlining the schema. In the framework I designed, user inputs are processed based on a contract file:

var jsonConfiguration = '{"withSection1": false}';

var contract = {
    withSection1: {
        type: 'boolean',
        default: true
    },
    withSection2: {
        type: 'boolean',
        default: true
    },
    withSection3: {
        type: 'boolean',
        default: false
    },
    withSection4: {
        type: 'boolean',
        default: true
    }
}

// Check types, assign default values when necessary, ...
var configuration = processConfiguration(jsonConfiguration, contract);

drawScreen(configuration);

function processConfiguration(jsonConfiguration, contract) {
    var configuration = JSON.parse(jsonConfiguration),
        processedConfiguration = {}
    ;

    for (var key in contract) {
        if (undefined === configuration[key]) {
            processedConfiguration[key] = contract[key].default;
        } else {
            processedConfiguration[key] = configuration[key];
        }
    }

    return processedConfiguration;
}

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

Modify the divs in two separate occasions when submitting different forms

Within my form, I have radio buttons located inside div1, a captcha code to be solved in div2, and additional content in div3. My goal is to have div1 replaced by div2 when a radio button is checked and submitted. Then, after completing the captcha in div2 ...

Content in static JSON file failing to display in NextJS

I recently started using Next, and I've encountered an issue. There is a static JSON file located in the root of my project directory, structured as follows: {"data":[{"id":1,"attributes":{"name":"Test Prod ...

I'm looking for a way to retrieve a specific item from a JSON array based on its ID within a NEXT.js

I'm completely new to using Next.js and I'm currently working on fetching data from an API. Specifically, I have a list of movies and my goal is to be able to select one movie and display its image on a separate page. I believe that I need to uti ...

How to dynamically reduce the number of columns in a textarea using jQuery according to its content

Does anyone know how to make a textarea shrinkwrap the text inside on blur? The default number of columns is 10 or 15 and I want the textarea to adjust its width based on the text content. I have tried the following code: $('textarea').on(&apos ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

Submit information to the database using JSON format

How can I utilize AJAX, JSON, and PHP to upload data to a database? See the code snippet below. AJAX function saveToTheDB(ratedIndex) { $.ajax({ url: 'fetch.php', method: 'POST', cache: ...

In all tests, except for the initial one, the DOM is not updated by test-utils once triggers have been fired

I have been facing an issue with checking for error messages related to field completion in HTML/DOM after vuelidate is triggered. The functionality works properly after the click trigger, and all tests pass successfully - including mounting, element searc ...

Locate every item that has a value that is not defined

My data is stored in indexeddb, with an index on a text property of the objects. I am trying to retrieve all objects where this property's value is undefined. I have been experimenting with IDBKeyRange.only(key), but when I use null, undefined, or an ...

Error code 3840: The task could not be fulfilled due to Cocoa error

Connecting to my localhost API (which I am in the process of developing for an iOS Swift app) to retrieve a JSON string. The API is built using the Laravel 4 framework. Below is the iOS Swift code snippet for establishing the connection and retrieving dat ...

Tips for utilizing JavaScript getElementByClassName to retrieve all the elements within a ul without having to specify the class name in each li

Looking to tidy up my HTML/CSS. Is there a way to keep this JavaScript functioning without needing to add the class name to every li element within the ul? Any suggestions on how to improve the visual appeal and readability of the HTML code? const Profi ...

Koajs functions yield their return values

When working with expressjs, I typically utilize asynchronous functions as shown below: function foo(callback) { var bar = {a: 1, b: 2}; callback(null, bar); } foo(function(err, result) { // result is {a: 1, b: 2} }); In Koajs, I use the yield wit ...

Error: The dynamic selection function is experiencing an issue where it is unable to read the "map" property of an undefined

Currently, I am in the process of creating a React component that includes the usage of a select HTML input. The implementation is defined as shown below: <select className="form-control-mt-3" id="clientList" name="clientList" onChange={this.handleC ...

Is there a way to submit the value of a textbox that has been generated dynamically using jQuery?

I am currently using the CodeIgniter framework and am attempting to incorporate textboxes in an HTML form. When the user clicks a button, a new textbox should be generated automatically using jQuery. However, when I submit the form, the values of the dynam ...

Unexpected anomaly with Jquery's after() method

Currently, I am working on the following task: I want to dynamically add a new student to a table of existing students using AJAX when a student is added through my user interface. The process involves sending the UI input fields to the controller, which ...

Creating an element in jQuery without the need for a closing tag

My situation requires dynamically building HTML elements using jQuery. Firstly, I initiate the process with the following function: function createSection(divName) { $("#"+ divName).append("<section id='team' class='pb-5'>&b ...

Having trouble deserializing the POJO that was sent from an Angular HTTP post request within my Spring Boot POST-mapped function

My application is a coffee shop, and I am trying to send an array of items to my Spring Boot backend. However, Jackson is throwing an exception: Cannot construct instance of `me.andrewq.coffeeshop.menu_items.Menu` (no Creators, like default constructor, e ...

JavaScript has encountered a syntax error

When working on an animation in javascript, I encountered a problem that I can't seem to identify. I am attempting to make the pan function work with the "mover" function, but it seems like either I am not using the properties correctly within the "tr ...

What is the process for assigning default values to dynamically generated form elements?

I have been working on building a single-page application (SPA) using JavaScript and jQuery. During the process, I encountered an issue with a dynamic form. The user is able to add specific fields as needed, but if they don't generate and utilize all ...

Adding items to an array within another array in React

I have a collection of objects structured like this: { pksites: number; rooms: Room[]; } I am attempting to append the rooms to each object in the collection. Here is my implementation: collectionOfObjects.forEach((obj) => { obj.rooms ...

Error in ElectronJS: Trying to access properties that are not defined (specifically 'whenReady')

Below is a straightforward code snippet: function myFunction() { const { app, BrowserWindow } = require('electron') const createWindow = () => { const win = new BrowserWindow({ width: 800, height: 600 ...