几种常见的JSON数据格式化

一、格式化化后不可修改   
<pre>{{ JSON.stringify(inputData, null, 4) }}</pre> <!--格式化json数据,inputData为json对象-->

二、格式化后可修改数据

       方式1:

<template>
  <div class="content">
    <el-button
      type="primary"
      size="mini"
      @click="saveMesg"
    >
      保存
    </el-button>
    <el-input
      type="textarea"
      class="leftInput"
      v-model="inputValue"
      @change="changeValue"
    ></el-input>
  </div>
</template>

<script>
  export default {
    name: 'Json',
    data() {
      return {
        inputValue: '',
        inputData: {
          'inputData-输入变量': {
            'applyInfo-申请信息': {
              'ApplyTime-申请时间': 'NA',
              'ChannelCode': 'NA',
              'IDCardNo': '2403242********340',
              'Age': 28
            },
            'DSWorkflow-客户信息': {
              'NextDSCods': 'node4',
              'StepNo': -999
            }
          }
        }
      };
    },
    mounted() {
      this.inputValue = JSON.stringify(this.inputData, null, 4)
    },
    methods: {
      changeValue() {
        if (this.inputValue && typeof (this.inputValue) === 'string') {
          try {
            let data = ''
            data = JSON.parse(this.inputValue)
            this.inputValue = JSON.stringify(data, null, 4)
          } catch (e) {
            this.$notify({
              title: '数据格式有误',
              type: 'error',
              duration: 2500
            })
            return true
          }
        }
      },
      saveMesg() {
        if (this.changeValue()) {
          return
        }
        // 将输入框里的内容转成字符串传给后端
        this.inputData = JSON.parse(this.inputValue)
        console.log(this.inputData)
      }
    }
  }
</script>

<style lang="scss">
  .content {
    margin-top: 10px;
    width: 400px;
    height: 500px;
  }
  .content .el-textarea__inner {
    margin-top: 10px;
    height: 380px;
    line-height: 20px;
  }
</style>

       方式2:

<template>
  <div class="content">
    <el-button
      type="primary"
      size="mini"
      @click="saveMesg"
    >
      保存
    </el-button>
    <el-input
      type="textarea"
      class="leftInput"
      v-model="inputValue"
      @change="changeValue"
    ></el-input>
  </div>
</template>

<script>
  export default {
    name: 'Json',
    data() {
      return {
        inputValue: '',
        inputData: {
          'inputData-输入变量': {
            'applyInfo-申请信息': {
              'ApplyTime-申请时间': 'NA',
              'ChannelCode': 'NA',
              'IDCardNo': '2403242********340',
              'Age': 28
            },
            'DSWorkflow-客户信息': {
              'NextDSCods': 'node4',
              'StepNo': -999
            }
          }
        }
      };
    },
    mounted() {
      // 将json数据转成字符串显示在输入框里
      this.inputValue = this.format(JSON.stringify(this.inputData))
    },
    methods: {
      changeValue() {
        if (this.inputValue && typeof (this.inputValue) === 'string') {
          try {
            this.inputValue = JSON.parse(this.inputValue)
            this.inputValue = this.format(JSON.stringify(this.inputValue))
          } catch (e) {
            this.$notify({
              title: '数据格式有误',
              type: 'error',
              duration: 2500
            })
            return true
          }
        }
      },
      // 格式化json数据
      format(str){
        var stack = []; //栈-用于括号匹配
        var tmpStr = '';    //新格式化JSON字符串
        var len = Object.keys(str).length;   //原始JSON长度

        //遍历每一个字符
        for (let i = 0; i < len; i++) {

          //当遇到结构块起始结构
          if (str[i] == '{' || str[i] === '[') {

            //起始结构后面直接换行
            tmpStr += str[i] + "\n";

            //入栈
            stack.push(str[i]);

            //这里的意思是结构块起始的下一行开始就会有一个缩进,缩进量与遇到的结构块起始符个数成正比1:1
            tmpStr += "\t".repeat(stack.length);
          }
          //当遇到结构块结束符
          else if (str[i] == ']' || str[i] === '}') {

            //因为本身JSON格式是固定的,所以括号一定是成对的,这里先不考虑错误的json数据
            //遇到结束符就退栈,
            stack.pop();

            //结束符本身输出到下一行,并减少一个缩进
            tmpStr += "\n"+"\t".repeat(stack.length) + str[i];
          }
          //当遇到逗号的时候
          else if (str[i] == ',') {
            //逗号后方直接换行,以及下一行的缩进处理
            tmpStr += str[i] + "\n" + "\t".repeat(stack.length);
          }
          else {
            //其他字符直接复制
            tmpStr += str[i];
          }
        }
        return tmpStr;
      },
      saveMesg() {
        if (this.changeValue()) {
          return
        }
        // 将输入框里的内容转成字符串传给后端
        this.inputData = JSON.parse(this.inputValue)
        console.log(this.inputData)
      }
    }
  }
</script>

<style lang="scss">
  .content {
    margin-top: 10px;
    width: 400px;
    height: 500px;
  }
  .content .el-textarea__inner {
    margin-top: 10px;
    height: 380px;
    line-height: 20px;
  }
</style>

 


版权声明:本文为fendoudemayi159原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。