FSAAdmin
asked on
Create JSON from HTML form using JavaScript
I need to build an html form that collects data entered from the user and then creates json to be used for an API call. The format that the JSON needs to placed in is hierarchical and I'm not sure how to do that.
This is what the JSON should look like and each value should be coming in from the html form.
This is what the JSON should look like and each value should be coming in from the html form.
{
"request": {
"subject": "Unable to fetch mails",
"description": "I am unable to fetch mails from the mail server",
"requester": {
"id": "4",
"name": "administrator"
},
"impact_details": "Routine tasks are pending due to mail server problem",
"resolution": {
"content": "Mail Fetching Server problem has been fixed"
},
"status": {
"name": "Open"
}
}
}'
ASKER
Zvonko thank you for the reply. I'm new to JSON so that is part of my struggle. I'm trying to use this script to form the JSON from the form elements. I can pass in the value and input name to create the JSON but I'm unable to structure it in the format that the API is expecting.
document.getElementById("button1").onclick = function(e){
make_json(document.getElementById("data"));
}
function make_json(form){
var json={};
var elements = form.elements;
for (var i = 0, element; element = elements[i++];) {
if (element.type == "text" || element.type =="hidden" && element.value != ""){
json[element.name] = element.value;
}
}
var input_data = JSON.stringify(json,null,4);
document.getElementById('output').innerHTML=html;
return false;
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you that helps a ton. Now we get to move on to pass the json with other Paramaters to the API.
If your question is: Can some HTML form be structured to convert its fields, selects and so on to result in upper Object?, then is the answer: No
So you have to map your regular html form fields to your upper Object that you want to send as JSON.
Here a HTML translation of your JSON:
https://codebeautify.org/json-to-html-converter/cbe2fc8d