将看起来像js对象的数据转换成json数据

203 阅读2分钟

作为前端的你,是否遇到过调用后端接口的时候出错,跟后端说解决一下,却要你把传入数据发过去的情况,而且还一个劲地要json数据。而你又恰恰很懒,不想再重复这个报错地流程,那么接下来的代码可能会对你有所帮助。

运行网页后,可以看到两个框和一个按钮,左边的是一个输入框,将开发者工具network面板下出错api底部的数据拷贝进来,再点击“转化”按钮,就可以实现将出错按钮转化成json数据。不过目前只能处理简单的数据,不能处理嵌套对象和数组的情况。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    html {
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .container {
      width: 80vw;
      min-width: 800px;
      height: 80vh;
      display: flex;
      justify-content: space-between;
      align-items: stretch;
    }

    .content-box {
      width: 45%;
      min-width: 460px;
      min-height: 340px;
      padding: 10px;
      font-size: 18px;
    }

    .left {
      border: 1px solid blue;
    }

    .right {
      border: 1px solid red;
      white-space: pre;
    }

    button {
      align-self: center;
      background-color: blueviolet;
      padding: 5px 20px;
      border: 1px;
      border-radius: 5px;
      color: white;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="left content-box" contenteditable></div>
    <button>转化</button>
    <div class="right content-box"></div>
  </div>

  <script>
    let left = document.querySelector('.left')
    let right = document.querySelector('.right')
    let button = document.querySelector('button')

    button.addEventListener('click', () => {
      right.innerText = format(left.innerText)
    }, false)


    /*
     * 将看起来像json字符串的字符串修改成真正的字符串
     * str {string} 待处理的字符串,可能是多行的
     */
    function format(str) {
      let reg = /["\s]*(?<prop>[\w]*)["]*[::][\s]*(?<value>.*)/
      let obj = {}
      str.split('\n').forEach(ele => {
        // debugger
        let matched
        let prop
        let value
        if (ele.trim()) {
          matched = ele.trim().match(reg)
          if (matched && matched.groups && matched.groups.prop && matched.groups.value) {
            prop = matched.groups.prop
            value = matched.groups.value
            prop = prop.trim()
            value = value.trim()
            // debugger
            if (/^["']+([\d.]*)["']+$/.test(value)) { // 在数字的左右两边各有一个双引号
              value = value.replace(/"?([\w]*)"?/, "$1")
            } else if (/^"?([\d.]*)"?$/.test(value)) { // 在数字的左边或右边有一个双引号或没有
              value = value.replace(/^"*([\d.]*)"*$/, "$1")
              value = Number.parseFloat(value)
            } else if(/^"?([\d.]*)"?$/.test(value)){

            }
            
            else { // 单纯的字符串左右两侧有双引号
              value = value.replace(/"*([\w:/.\\\-]*)"*/, "$1")
            }
            obj[prop] = value
          }
        }
      })
      return JSON.stringify(obj, '', 2)
    }

    // "    "name: "Tom""
  </script>
</body>

</html>