因为专注,所以专业
2005 - 2020

js实现json格式化,以及json校验工具的简单实现

时间:2020-02-05 16:49:06    作者:八叔模板堂

一.json结构及形式

{ "firstName": "Brett", "lastName":"McLaughlin", "email": "aaaa" }
[
    {
        key1:value1,
        key2:value2 
    },
    {
         key3:value3,
         key4:value4   
    }
]

二.json字符串转化为json对象

var json_text = "{'book':{'name':'JAVA编程','author':['Liu','Xu']},'num':222}";
<script type="text/javascript">
    window.onload = function(){
       var json_text = "{'book':{'name':'JAVA编程','author':['Liu','Xu']},'num':222}";
       //使用eval()将字符串转换为对象
       var json_obj = eval("("+ json_text +")");
       //访问 book-name
       document.write(json_obj.book.name);
       //访问 book-author-Xu
       document.write(json_obj.book.author[1]);
    } 
  </script>
<script type="text/javascript">
    window.onload = function(){
       var json_text = "{'book':{'name':'JAVA编程','author':['Liu','Xu']},'num':222}";
       //用new Function将字符串转换为对象
       var json_obj = (new Function("return" + json_text))();
       //访问 book-name
       document.write(json_obj.book.name);
       //访问 book-author-Xu
       document.write(json_obj.book.author[1]);
    } 
  </script>
<script type="text/javascript">
    window.onload = function(){
       var json_text = '{"book":"js"}';
       //用全局JSON将字符串json转换为json对象
       var json_obj = JSON.parse(json_text);
       //访问 book-name
       document.write(json_obj.book);
       //访问 book-author-Xu
       //document.write(json_obj.book.author[1]);
    } 
  </script>

三.json校验格式化工具简单实现

<body> 
  <textarea id="content_value">
  </textarea>
  <input type="button" value="格式化" onclick="check()">
  <textarea id="output_value">
  </textarea>
</body> 
<script type="text/javascript">
function check(){
  var text_value = document.getElementById('content_value').value;
  if(text_value == ""){
     alert("不能为空");  
     return false;
  } else {
        var res="";
        for(var i=0,j=0,k=0,ii,ele;i<text_value.length;i++)
        {//k:缩进,j:""个数
            ele=text_value.charAt(i);
            if(j%2==0&&ele=="}")
            {
                k--;                
                for(ii=0;ii<k;ii++) ele="    "+ele;
                ele="\n"+ele;
            }
            else if(j%2==0&&ele=="{")
            {
                ele+="\n";
                k++;     
                debugger;       
                for(ii=0;ii<k;ii++) ele+="    ";
            }
            else if(j%2==0&&ele==",")
            {
                ele+="\n";
                for(ii=0;ii<k;ii++) ele+="    ";
            }
            else if(ele=="\"") j++;
            res+=ele;        
        }
      document.getElementById('output_value').value = res;
  }
}
</script>
赞(0
免费拨打  111-1111-1111
免费拨打  111-1111-1111免费拨打 111-1111-1111
微信二维码
手机二维码
返回顶部
返回顶部返回顶部