vue 判断字符串是否为json格式,json字符串格式化
判断字符串是否为json格式和格式化我写在一起了js代码:aaa(){//判断字符串是否为json格式try{var obj = JSON.parse(this.jsonString)if(typeof obj == 'object' && obj){//对字符串进行格式化展示var nbsp = " "
·
判断字符串是否为json格式和格式化我写在一起了
js代码:
aaa(){
//判断字符串是否为json格式
try{
var obj = JSON.parse(this.jsonString)
if(typeof obj == 'object' && obj){
//对字符串进行格式化展示
var nbsp = " "
var num = 0
var jsonend = ""
var array = this.jsonString.split('')
for(var i = 0; i < array.length; i++){
if(array[i] === '{'){
num = num + 1
jsonend = jsonend + array[i] + '<br/>'
var temp = num
while(temp > 0){
jsonend = jsonend + nbsp
temp = temp - 1
}
}else if(array[i] === '}'){
num = num - 1
jsonend = jsonend + '<br/>'
var temp = num
while(temp > 0){
jsonend = jsonend + nbsp
temp = temp - 1
}
jsonend = jsonend + array[i]
}else if(array[i] === '['){
num = num + 1
jsonend = jsonend + array[i] + '<br/>'
var temp = num
while(temp > 0){
jsonend = jsonend + nbsp
temp = temp - 1
}
}else if(array[i] === ']'){
num = num - 1
jsonend = jsonend + '<br/>'
var temp = num
while(temp > 0){
jsonend = jsonend + nbsp
temp = temp - 1
}
jsonend = jsonend + array[i]
}else if(array[i] === ','){
jsonend = jsonend + array[i] + '<br/>'
var temp = num
while(temp > 0){
jsonend = jsonend + nbsp
temp = temp - 1
}
}else{
jsonend = jsonend + array[i]
}
}
//格式化完成,写入到页面
document.getElementById("qwer").innerHTML = jsonend
}else{
document.getElementById("qwer").innerHTML = "格式错误"
}
}catch(error){
document.getElementById("qwer").innerHTML = "格式错误"
}
}
vue代码:
<el-button type="primary" @click="aaa">aaa</el-button><!--绑定js方法-->
<el-card class="box-card">
<div slot="header" class="clearfix">
<span>格式化后</span>
</div>
<div id="qwer"></div><!--id要和js中document.getElementById里的id一致-->
</el-card>
效果图:
更多推荐
已为社区贡献6条内容
所有评论(0)