You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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 a type property ("AND"/"OR") and a children array 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 jsonToHtml to 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 JSON type values aligned to avoid conversion errors.
  • Validation: Add checks for valid type values in both functions to handle edge cases (e.g., invalid JSON or malformed HTML).

内容的提问来源于stack exchange,提问作者Максим Устелемов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:04:47