JSON字符格式化后在前端展示或者格式化文本域的JSON

 repeat (s, count) {
      return new Array(count + 1).join(s)
    },
    formatJson (json) {
      var i = 0,
        il = 0,
        tab = "    ",
        newJson = "",
        indentLevel = 0,
        inString = false,
        currentChar = null;
      for (i = 0, il = json.length; i < il; i += 1) {
        currentChar = json.charAt(i);
        switch (currentChar) {
          case '{':
          case '[':
            if (!inString) {
              newJson += currentChar + "\n" + this.repeat(tab, indentLevel + 1);
              indentLevel += 1
            } else {
              newJson += currentChar
            } break;
          case '}':
          case ']':
            if (!inString) {
              indentLevel -= 1;
              newJson += "\n" + this.repeat(tab, indentLevel) + currentChar
            } else {
              newJson += currentChar
            }
            break;
          case ',':
            if (!inString) {
              newJson += ",\n" + this.repeat(tab, indentLevel)
            } else {
              newJson += currentChar
            }
            break;
          case ':':
            if (!inString) {
              newJson += ": "
            } else {
              newJson += currentChar
            }
            break;
          case ' ':
          case "\n":
          case "\t":
            if (inString) {
              newJson += currentChar
            }
            break;
          case '"':
            if (i > 0 && json.charAt(i - 1) !== '\\') {
              inString = !inString
            }
            newJson += currentChar;
            break;
          default:
            newJson += currentChar;
            break
        }
      }
      return newJson
    },
    getFormatData (json) {
      var json = json + "";
      if (json.indexOf('{') == -1 && json.indexOf('[') == -1) {
        return json;
      } else {
        return (this.formatJson(json));
      }
    }

在vue中使用的,调用方法为this.getFormatData (json)
如图所示JSON字符格式化后在前端展示或者格式化文本域的JSON_第1张图片

你可能感兴趣的:(html,vue,JSON)