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?