美文网首页
笔试题: 实现一个js 解析器 将以下的文本解析为 json对象

笔试题: 实现一个js 解析器 将以下的文本解析为 json对象

作者: 杨同学a | 来源:发表于2023-08-20 19:51 被阅读0次
 // 题目 实现一个js 解析器 将以下的文本解析为 json对象数据
  const html = `view{
                  heading{}
                  text{}
                }`
// 结果
  const json ={
    'tagName':'view',
    'children':[
      {
        'tagName':'heading',
        'children':[]
      },
      {
        'tagName':'text',
        'children':[]
      }
    ]
  }

答案: 来自某个大佬提供的思路

function parseHTML(html) {
    const res = []
    parseHTMLTree(html, res)
    console.log(JSON.stringify(res, null, 2))
    return res
  }

  function parseHTMLTree(html, arr) {
    const reg = /\s*([A-Za-z][^{\s]*)\s*{/;
    let match = reg.exec(html)
    while (match) {
      const prev = match[0];
      const tagName = match[1];
      const startIndex = match.index;
      const endIndex = findNextCompare(html, startIndex)
      const tag = {
        tagName,
        children: []
      }

      arr.push(tag)
      const startItem = html.slice(prev.length + startIndex, endIndex)
      parseHTMLTree(startItem, tag.children)
      html = html.slice(endIndex + 1)
      match = reg.exec(html)
    }
  }

  function findNextCompare(str, startIndex, left = '{', right = '}') {
    let stack = [];
    for (let i = startIndex; i < str.length; i++) {
      if (str[i] === left) {
        stack.push(1)
      } else if (str[i] === right) {
        stack.pop()
        if (!stack.length) {
          return i
        }
      }
    }
  }


// 直接运行
parseHTML(html)

// 结果
[
  {
    "tagName": "view",
    "children": [
      {
        "tagName": "heading",
        "children": []
      },
      {
        "tagName": "text",
        "children": []
      }
    ]
  }
]

相关文章

网友评论

      本文标题:笔试题: 实现一个js 解析器 将以下的文本解析为 json对象

      本文链接:https://www.haomeiwen.com/subject/wotemdtx.html