json数据美化、解析

//方法一

/* 引入jquery.json-viewer.js 与jquery.json-viewer.css 文件
 * 给pre传入数据
 * *判断一下IE版本,如果是ie则直接展示,其他浏览器[火狐、IE edge、谷歌、360安全/急速...]可使用json-viewer.js
 */

<link href="jquery.json-viewer.css" type="text/css" rel="stylesheet" />

<pre id="json-renderer"></pre>

<script src="jquery.json-viewer.js"></script>


//方法二:在上面的方法加深

<script>
  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
  var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1; //判断是否IE<11浏览器  
  var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器  
  var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
  if(isIE||isIE11){
    $("#json-renderer").text(JSON.stringify(json, null, 5));      
  }else{
    $('#json-renderer').jsonViewer(json);
  }


function syntaxHighlight( json ){
  json = json.replace( /&/g, '&amp;' ).replace( /</g, '&lt;' ).replace( />/g, '&gt;' );
  return json.replace( /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function ( match )
  {
    console.log(match)
    var cls = 'number';
    if ( /^"/.test( match ) ) {
      if ( /:$/.test( match ) ){
        cls = 'key';
      } else{
        cls = 'string';
      }
    } else if ( /true|false/.test( match ) ){
      cls = 'boolean';
    } else if ( /null/.test( match ) ){
      cls = 'null';
    }
    return '<span class=" + cls + ">' + match + '</span>';
  });
}

 var str = JSON.stringify( json, undefined, 4 );
 $("#json-renderer").html( syntaxHighlight( str ));

});

</script>



//方法三:直接展示

return JSON.stringify(JSON.parse(JSON), null, 4);

// 解析JSON数据 - 推荐

/* $(json数组、function(key,val){}) */
$.each(json, function(key, val) {
    $(".html-result").append("<p>"+ key + ': ' + val+"</p>");
});

// 其他解析方法

var json= { "Type": "Coding", "Height":100 };

for (var key in json){
  console.log(key);   //Type, Height
  console.log(json[key]); //Coding, 100
}

$.each(json, function(i) {
    console.log(json[i]); //Coding, 100
    console.log(i);     //Type, Height
});

 

/*  for in 遍历整个原型链,性能差、好资源(数据少时可以使用)。

数据多时容易造成浏览器卡死,建议使用$.each(对象,function(index){}),  each()函数具有十分强大的遍历功能,可以遍历一维数组、多维数组、Dom、Json等。

*/

 

posted @ 2021-04-08 14:17  *玥  阅读(496)  评论(0)    收藏  举报