Generate JSON with a distinct structure

My goal is to send a JSON via POST request to an API in the following format:

"answer" => {
    "name"=>"Test", 
    "email"=>"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e52">[email protected]</a>", 
    "hospital"=>"Hospital Name", 
    "answered_questions_attributes"=>{
        "0"=>{
            "value"=>"1", 
            "question_id"=>"1"
        }, 
        "1"=>{
            "value"=>"0", 
            "question_id"=>"2"
        }, 
        "2"=>{
            "value"=>"1", 
            "question_id"=>"3"
        }
    }
}

To populate the "answered_questions_attributes" data, I extract values from inputs where the input name corresponds to the question ID and the value represents true or false. For example:

<div class="resp_val_div">
  <input type="hidden" name="1" value="1" />
  <input type="hidden" name="2" value="0" />
  <input type="hidden" name="3" value="1" />
</div>

I attempted the code snippet below, but it only returns an incorrect JSON structure:

var resp_val = jQuery(".resp_val_div").find("input");
var dados = {
    "name": jQuery("#name").val(),
    "email": jQuery("#email").val(),
    "hospital": jQuery(".answer_hospital").val(),
    'answered_questions_attributes':[]
};
resp_val.each(function(index, el) {
    d = {"value":parseInt(el.value), "question_id":el.name};
    dados.answered_questions_attributes.push(d);
});
console.log(dados);
"answer"=>{
    "name"=>"Test", 
    "email"=>"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="324657414672465741461c5">[email protected]</a>", 
    "hospital"=>"Hospital Test", 
    "answered_questions_attributes"=>[
        {
          "value"=>1,
          "question_id"=>"1"
        }, 
        {
          "value"=>0,
          "question_id"=>"2"
        }, 
        {
          "value"=>1,
          "question_id"=>"3"
        }
    ]
}

How can I properly create the initial JSON object in this scenario?

Answer №1

Avoid using an array and the .push() method if you need an object. Also, refrain from using parseInt() if you prefer the value property to remain a string instead of converting it to a number.

    var data = {
        "name": jQuery("#name").val(),
        "email": jQuery("#email").val(),
        "hospital": jQuery(".answer_hospital").val(),
        'answered_questions_attributes':{}
    };


    response_values.each(function(index, element) {
        entry = {"value":element.value, "question_id":element.name};
        data.answered_questions_attributes[index] = entry;
    });

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

"How can we pause the setInterval when the user hovers over the Ajax Quick Cart and resume it once

Currently, I am working on configuring my Ajax Quick Cart to delay a setInterval function when the user hovers over the cart. The goal is to have the cart close automatically after 3 seconds once an item has been added. However, as I'm not very profic ...

What are the steps to implement email validation, Saudi mobile number validation, and national ID validation in cshtml?

Looking to implement validations for the following fields: email, mobile number (must be 10 numbers and start with 05), and National ID (must be 10 numbers and start with 1 or 2) <input class="form-control" type="text" id="txt ...

The File plugin in Ionic 3 is encountering difficulties in writing files on the device

I am developing an app using Ionic 3 and the file plugin. My goal is to write a JSON string to a JSON file located in my assets folder with the following hierarchy: assets -> mock -> msg-list.json , with "assets" as the main folder in the Ionic file ...

Serializing Joda DateTime objects yields varying results based on the current context

I am facing a challenge with serializing and deserializing an object that contains a nested Joda DateTime object. When I attempt to serialize the entire object containing the DateTime, the output is significantly different from when I directly serialize t ...

serving files using express.static

I have set up express.static to serve multiple static files: app.use("/assets", express.static(process.cwd() + "/build/assets")); Most of the time, it works as expected. However, in certain cases (especially when downloading many files at once), some fil ...

"An error occurred: Attempting to access properties of an undefined object (specifically 'foundTicket'). While the getTickets() function, which fetches data from MongoDB using Mongoose, is working fine, the getTicketById()

I recently started working with next.js and I'm following a project tutorial by a YouTuber. Here is the link to my code: https://github.com/Fanguiee/ticketing-app/tree/edit-existing-item or you can also read below. Thank you in advance :) Screenshot: ...

Creating a BPMN web-based designer using JavaScript

In search of a web-based UI tool to design and save bpmn workflows as XML for integration with an Angular front end. As a starting point, I need to draw bpmn shapes. Does anyone have suggestions on the best method to accomplish this using JavaScript? I&apo ...

How to extract and process multiple values of the same key in a JSON file using

I'm new to working with JSON and I'm a bit confused about something. What I am attempting to do is to parse the following data: [{"name":"Djinnibone"},{"name":"Djinnibutt","changedToAt":1413217187000},{"name":"Djinnibone","changedToAt":141321720 ...

Using Flickity API in Vue 3 with Typescript Integration

I have encountered an issue with implementing Flickity in my Vue 3 application. Everything works perfectly fine when using a static HTML carousel with fixed cells. However, I am facing difficulties when attempting to dynamically add cells during runtime us ...

How do you display a nested object in React after merging it?

To display the JSON below as an image, click https://i.stack.imgur.com/tixu4.png let finalSplit = [ { start: "73", end: "76", splits: [ { word: "Now", start: "73", ...

Generating and displaying a JSON response

I am having trouble displaying a response on the screen using an AJAX request script with a post method and body value. Here is my code: $('#my-form').submit(function () { $.ajax({ url: 'https://apiurl.com/users', ...

Retrieve dynamic data from a website using jQuery's AJAX functionality

I am trying to retrieve the data from example.com/page.html. When I view the content of page.html using Chrome Browser, it looks like this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> & ...

The Controller is failing to pass JSON Data to the AJAX Call

When trying to access JSON data in the Controller, it is not being retrieved in the Success function and instead showing an error message "Failed to load resource: the server responded with a status of 406 (Not Acceptable)" or executing the Error function. ...

Retrieve secondary data points from a JSON object

I am in the process of creating selectboxes using information from a JSON string. I am trying to figure out how to extract the second level data from a string and incorporate it into the selectboxes. Here is an example: JSON { "product": { opt ...

The data display in MUI-Datatable is experiencing an issue where it is unable to read properties of undefined, specifically when trying to split the data

Whenever I include data within the MuiDatatable, it triggers this error: Cannot read properties of undefined (reading 'split') Is there a solution to this problem so that the data can be properly displayed? To demonstrate the issue, I have se ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...

Is it guaranteed that ajax will execute during beforeunload event?

I am developing an HTML5 application and I need to send a disconnect ajax request when the user changes or refreshes the page. Currently, I have implemented this code: window.addEventListener("beforeunload", function(event) { $.ajax({ url: api ...

Vuetify ensures that elements remain in a single row and adjust their size according to the content

I'm trying to create a layout with a single row that has a button aligned to the right edge, and the rest of the space filled with multiple buttons inside a v-chip-group. There are more buttons than can fit in the available space, so I want the v-chip ...

Is NodeJS primarily used as a socket library for network communication?

Here is a server program written in C language using socket functionality provided by libC # include <unistd.h> # include <sys/socket.h> # include <sys/types.h> # include <string.h> #include <netinet/in.h> main(){ int listfd ...

One interesting characteristic of Javascript localStorage is that it overrides existing data instead of adding to it

I've been experimenting with localStorage to create new divs dynamically. Everything is going well, but I encountered an issue after reloading the page and clicking the bag button again. The previously created divs are being replaced by the new ones i ...