基于HTML与JSON互转及层级<select>/<input>逻辑组技术咨询
HTML ↔ JSON Conversion for Condition Groups
Understanding the Structure
First, let's map the core HTML components to JSON entities clearly:
- A
<div class="conditions-group logical-and">or<div class="conditions-group logical-or">becomes a group object in JSON, with atypeproperty ("AND"/"OR") and achildrenarray holding nested groups or conditions. - A
<div class="condition row">becomes a condition object in JSON, containing values from its<select>/<input>elements (e.g.,field,operator,value).
1. Convert HTML to JSON
Here's a recursive JavaScript function to traverse your condition group HTML and build a structured JSON object. I'll assume your condition rows use classes like condition-field, condition-operator, and condition-value for easy value extraction—adjust selectors to match your actual markup.
Conversion Function
function htmlToJson(groupElement) { // Determine the logical type of the current group const type = groupElement.classList.contains('logical-and') ? 'AND' : 'OR'; const children = []; // Process each child element in the group's conditions container groupElement.querySelectorAll('.conditions > *').forEach(child => { if (child.classList.contains('conditions-group')) { // Recursively handle nested groups children.push(htmlToJson(child)); } else if (child.classList.contains('condition')) { // Extract values from the condition row children.push({ type: 'CONDITION', field: child.querySelector('.condition-field').value, operator: child.querySelector('.condition-operator').value, value: child.querySelector('.condition-value').value }); } }); return { type, children }; } // Usage example: const rootConditionGroup = document.querySelector('.conditions-group'); const conditionJson = htmlToJson(rootConditionGroup); console.log(JSON.stringify(conditionJson, null, 2));
Example JSON Output
{ "type": "OR", "children": [ { "type": "AND", "children": [ { "type": "CONDITION", "field": "age", "operator": ">", "value": "18" }, { "type": "CONDITION", "field": "country", "operator": "=", "value": "USA" } ] }, { "type": "CONDITION", "field": "status", "operator": "=", "value": "active" } ] }
2. Convert JSON to HTML
Now let's reverse the process: take the JSON structure and generate the corresponding condition group HTML.
Conversion Function
function jsonToHtml(json) { // Create the root group element const groupDiv = document.createElement('div'); groupDiv.className = `conditions-group logical-${json.type.toLowerCase()}`; // Create the conditions container wrapper const conditionsDiv = document.createElement('div'); conditionsDiv.className = 'conditions'; groupDiv.appendChild(conditionsDiv); // Process each child in the JSON json.children.forEach(child => { if (child.type === 'AND' || child.type === 'OR') { // Recursively build nested groups conditionsDiv.appendChild(jsonToHtml(child)); } else if (child.type === 'CONDITION') { // Build a single condition row const conditionRow = document.createElement('div'); conditionRow.className = 'condition row'; // Add field dropdown (replace options with your actual fields) const fieldSelect = document.createElement('select'); fieldSelect.className = 'condition-field'; ['age', 'country', 'status'].forEach(opt => { const option = document.createElement('option'); option.value = opt; option.textContent = opt; if (opt === child.field) option.selected = true; fieldSelect.appendChild(option); }); // Add operator dropdown (replace options with your actual operators) const operatorSelect = document.createElement('select'); operatorSelect.className = 'condition-operator'; ['=', '>', '<', '!='].forEach(opt => { const option = document.createElement('option'); option.value = opt; option.textContent = opt; if (opt === child.operator) option.selected = true; operatorSelect.appendChild(option); }); // Add value input const valueInput = document.createElement('input'); valueInput.className = 'condition-value'; valueInput.type = 'text'; valueInput.value = child.value; // Append all elements to the condition row conditionRow.appendChild(fieldSelect); conditionRow.appendChild(operatorSelect); conditionRow.appendChild(valueInput); conditionsDiv.appendChild(conditionRow); } }); return groupDiv; } // Usage example: const conditionJson = { /* Your condition JSON here */ }; const generatedHtml = jsonToHtml(conditionJson); document.body.appendChild(generatedHtml);
Customization Tips
- Update the dropdown options in
jsonToHtmlto match your actual field and operator values. - Add any extra elements (like labels, delete buttons) to the condition row creation block if your UI requires them.
- Adjust class names to match your existing HTML structure for seamless integration.
Key Notes
- Recursion: Both functions use recursion to handle arbitrarily nested condition groups, which is critical for maintaining the hierarchical structure.
- Consistency: Keep your HTML class names (e.g.,
logical-and) and JSONtypevalues aligned to avoid conversion errors. - Validation: Add checks for valid
typevalues in both functions to handle edge cases (e.g., invalid JSON or malformed HTML).
内容的提问来源于stack exchange,提问作者Максим Устелемов
相关产品推荐
相关产品推荐

