如何让HTML表单适配嵌套结构的JSON Schema(JavaScript)
Got it, let's get your form and JavaScript logic aligned with the target JSON schema. We need to handle both the nested person object and the addressDetails array—here's how to do it step by step:
1. Update HTML Input name Attributes
First, we'll use bracket notation in the input names to map directly to the nested structure. This gives our JavaScript clear instructions on how to assemble the final JSON:
<div class="form-group"> <label for="caseIdentifier">First Name</label> <input type="text" class="form-control" id="firstname" name="person[firstName]"> </div> <div class="form-group"> <label for="lastName">Last Name</label> <input type="text" class="form-control" id="lastName" name="person[lastName]"> </div> <div class="form-group"> <label for="line1">Line 1</label> <input type="text" class="form-control" id="line1" name="addressDetails[0][line1]"> </div> <div class="form-group"> <label for="line2">Line 2</label> <input type="text" class="form-control" id="line2" name="addressDetails[0][line2]"> </div>
person[firstName]maps directly to the nestedperson.firstNameproperty in your schemaaddressDetails[0][line1]targets the first element (index 0) of theaddressDetailsarray, then itsline1property
2. Adjust JavaScript Form Handling Logic
The default FormData.forEach approach only creates a flat object, so we need a helper function to parse the bracket notation names into nested objects and arrays. Here's the updated, working code:
const myForm = document.getElementById('myForm'); myForm.addEventListener('submit', function (e) { e.preventDefault(); const url = 'YOUR_API_URL_HERE'; // Replace with your actual API endpoint const formData = new FormData(this); // Helper function to build nested objects/arrays from form data keys function buildNestedObject(formData) { const result = {}; formData.forEach((value, key) => { // Split key into parts (e.g., "person[firstName]" → ["person", "firstName"]) const keys = key.match(/([^\[\]]+)/g); let current = result; keys.forEach((part, index) => { // Check if the part is an array index (numeric) const isArrayIndex = !isNaN(parseInt(part)); const keyPart = isArrayIndex ? parseInt(part) : part; // Assign value if it's the final key part if (index === keys.length - 1) { current[keyPart] = value; } else { // Initialize nested object/array if it doesn't exist yet if (!current[keyPart]) { current[keyPart] = isArrayIndex ? [] : {}; } current = current[keyPart]; } }); }); return result; } const object = buildNestedObject(formData); const json = JSON.stringify(object); const fetchData = { method: 'POST', body: json, headers: { 'Content-Type': 'application/json' // Critical header for JSON payloads } }; fetch(url, fetchData) .then(function (response) { console.log('Request sent:', fetchData); return response.text(); }) .then(function (text) { console.log('Response received:', text); }) .catch(function (error) { console.error('Submission error:', error); }); });
Key Changes Explained:
- The
buildNestedObjectfunction parses each input's name into the correct nested structure, handling both objects and arrays. - It detects numeric key parts (like
0inaddressDetails[0]) and initializes an array instead of an object for those cases. - We added the
Content-Type: application/jsonheader to ensure the server recognizes the payload as valid JSON.
Test the Output
After filling out the form and submitting, the json variable will exactly match your target schema:
{ "person": { "firstName": "Kay", "lastName": "Young" }, "addressDetails": [ { "line1": "line1", "line2": "line2" } ] }
内容的提问来源于stack exchange,提问作者Eddy_Kay

