Tips for enhancing a JSON array by including attributes through JavaScripts

I need help in dynamically constructing JSON using Javascript.

{    
    "Events": [{
        "Name": "Code Change",
        "Enabled": "true",
        "Properties": [{
            "Name": "url",
            "Value": "val"
        }]
    }],
    "Properties": [{
        "Name": "url",
        "Value": "val"
    }]    
} 

The code I have written creates JSON with separate curly brackets for Name, Enabled, and properties. Is there a way to resolve this without using the push method?

Here is the code:

var eventProperties="[{'Name':'url','Value':'val'}]";
var subscriptionProperties="[{'Name':'url','Value':'val'}]";

var eventArray = JSON.parse('[1, 5, "false"]');
var subArray = JSON.parse('[1, 5, "false"]');


var subscription = {
    Events: [],
    Properties: []
};

if(eventName != null && eventName != "") {
    subscription.Events.push({
        "Name" : eventName
    });
}

var index = 0;

if(eventEnabled != null && eventEnabled != "") {
    subscription.Events.push({
        Enabled: eventEnabled
    });
}

if(eventProperties != null && eventProperties != "") {
    subscription.Events.push({
        "Properties": eval('(' + eventProperties + ')')
    });
} 

if(subscriptionProperties != null && subscriptionProperties != "") {
    subscription.Properties = eval('(' + subscriptionProperties + ')');
}

Current Output:

{    
    "Events": [{
        "Name": "Code Change"
     },
     {
        "Enabled": "true"
     },
     {
        "Properties": [{
            "Name": "url",
            "Value": "val"
        }]
     }],    
     "Properties": [{
         "Name": "url",
         "Value": "val"
     }]
} 

Answer №1

A single object can be created as shown below:

subscription.Events.push({
    Name: eventName,
    Enabled: eventEnabled,
    Properties: JSON.parse(eventProperties)
 });

Alternatively, you can follow the existing process like this:

 var subscription = {};

 var eventObject = {};

 if(eventName != null && eventName != "") {
     eventObject.Name = eventName;
 }

 if(eventEnabled != null && eventEnabled != "") {
     eventObject.Enabled = eventEnabled;
 }

 if(eventProperties != null && eventProperties != "") {
     eventObject.Properties = JSON.parse(eventProperties);
 }

 subscription.Events = [eventObject];

 if(subscriptionProperties != null && subscriptionProperties != "") {
     subscription.Properties = JSON.parse(subscriptionProperties);
 }

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

AngularJS fails to display JSON data

I've been experimenting with AngularJS by creating a basic gallery that pulls images from a JSON file, but for some reason I'm having trouble displaying the data. index.html: <!DOCTYPE html> <html ng-app="portfolioApp"> <head> ...

Best practices for making an AJAX call to fetch information from a database

I have a database containing a single table. The table includes columns for Company and Time, among others, with Company and Time being crucial. Users can make appointments by filling out a form. Within the form, there are 2 <select> elements - one ...

Tips for utilizing global functions in VUE 2 CLI crowd

I have multiple components that require the same functions. Is there a way to avoid duplicating the code in each component and instead use it globally...? Even if I put the function in the App.vue, it still isn't accessible in the components. ...

Caution: Prop type validation failed due to an invalid value being passed to ForwardRef(Slider)

Currently, I'm in the process of building a Material UI range Slider with two values. It functions correctly if initialized like this: const [value, setValue] = React.useState([5,20]); const [value, setValue] = React.useState([val]); const handl ...

Having trouble with Socket.io and its io.emit() method refusing to work? If communication from server to client isn't going smoothly, you may need a solution for sending data from the server to

My latest project is a document converter program that utilizes LibreOffice to convert documents to PDF format. Here's my server running on localhost:3000 import express from "express"; import bodyParser from "body-parser"; import ...

Utilize a single WebAssembly instance within two separate Web Workers

After compiling a wasm file from golang (version 1.3.5), I noticed that certain functions using goroutines are not supported. When these functions are called, they run in the current thread and slow down my worker significantly. To address this issue, I w ...

After receiving the go-ahead from JavaScript, I am planning on integrating PHP into my project. I have come across some recommendations

Looking for assistance with AJAX functionality on a website. Specifically, users should be prompted to confirm a purchase before completing it. If they confirm, the purchase goes through; if they decline, it does not. Originally considered using PHP within ...

Selecting Objects with a Mouse in Three.js

Thanks to the wonderful support from the stackoverflow community, I was able to successfully implement a basic object picking example. You can view the functional code here. However, it's important to note that this example specifically works when t ...

The process of transmitting messages back and forth between a popup script and a content script

I am in the process of developing a Chrome extension that involves sending data requests from a popup script to a content script (via a background script), analyzing the request on the content script, and then sending back a response (again through the bac ...

Utilizing javascript to reverse an array and seamlessly filling in the missing elements

Consider an array containing data with increasing percentage values and some missing entries. For instance: { "months": 11, "factor": 1.31, "upperMonths": 10.5, "lowerMonths": 11.49, "limit": 20, "percentage": 8 }, { "mont ...

hapi-auth-cookie: encounters an issue while trying to read cookies for accessing restricted content

I've implemented hapi-auth-cookie for managing cookies and sessions on my website. Certain parts are restricted and can only be accessed after authentication. When a non-logged-in user tries to access these areas, they are redirected to the login rout ...

Fetch search results dynamically in Wordpress through AJAX

I'm struggling to implement AJAX on my WordPress site to display search results without refreshing the page. Despite trying various solutions found through research, none seem to be working effectively for me. Currently, here is the progress I have ma ...

How can I retrieve the reference number of an item by clicking a button within a list item in an unordered

Presented here is a collection of data points and a button nested within an ul <ul> <li class="mix" category-1="" data-value="600.35" style="display:block;"> <figure> <figcaption> <h3> ...

Passing PHP array to JavaScript and selecting random images from the array

Check out my PHP script below: <?php $all_images = glob("Images/Classes/{*.png, *.PNG}", GLOB_BRACE); echo json_encode($all_images); shuffle($all_images); ?> Here's the JavaScript code I'm using: functio ...

Receiving JSON objects from Javascript in Django Views

When I attempt to pass a Json Object value from making an API call to my views.py in Django template, I encounter difficulty retrieving the value after an ajax call. let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = a ...

Is it possible to modify @page directive(CSS) values from the code-behind(C#) or JavaScript?

Using the @page directive, you can define the printer margins for a page separately from regular CSS margins: <style type="text/css" media="print"> @page { size: auto; /* auto is the current printer page size */ margin ...

Retrieve data from jQuery and send it to PHP multiple times

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" /> By using jQuery, I am able to extract multiple values from the table above once the checkboxes are checked. Here's how: var te ...

The normalizeResponse function should always provide a properly formatted JSON API document:

Check out my Code: In the model section: import Model, { attr } from '@ember-data/model'; export default class TodoModel extends Model { @attr('number') userId; @attr('string') title; @attr('boolean') complet ...

Tips for resolving the error message "cannot find module './node'" when compiling with pkg:

After successfully running my Node.js script with 'node main.js', I encountered an error when trying to compile it into an executable using pkg: pkg/prelude/bootstrap.js:1876 throw error; ^ Error: Cannot find module './node' Require s ...

You have encountered an error: [ERR_HTTP_HEADERS_SENT]. This means that you cannot set headers after they have already been sent to the client, even if a return

I've encountered a 'Cannot set headers after they are sent to the client' error with the /api/users/profile route and have been attempting to resolve it. I stumbled upon some solutions on stackoverflow suggesting to add a return statement - ...