校验字符串是否是JSON格式,将不规则展示的json格式的字符串进行规则展示(json格式化)

 

目录(?)[+]

 

 

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. var str = {"code": "","svcname": "","version": "","component": "","category": "","requestMsg": [{"fieldName": "userName","type": "simple","required": "true"},{"fieldName": "age","type": "simple","required": "true"}]}  

 

一、校验字符串是否是JSON格式:

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. function isJsonFormat(str) {  
  2.     try {  
  3.         $.parseJSON(str);  
  4.     } catch (e) {  
  5.         return false;  
  6.     }  
  7.     return true;  
  8. }  


二、将json格式的字符串格式化输出,先将json字符串转为对象,然后将此对象以json格式化输出:

 
[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. JSON.stringify(JSON.parse(json), null, "\t")  
 
[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. JSON.stringify(JSON.parse(json), null, 4)  



PS:\t:代表缩进一个tab;4:代表缩进4个空格
 
 
格式化后的输出:
[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. {  
  2.     "code": "",  
  3.     "svcname": "",  
  4.     "version": "",  
  5.     "component": "",  
  6.     "category": "",  
  7.     "requestMsg": [  
  8.         {  
  9.             "fieldName": "userName",  
  10.             "type": "simple",  
  11.             "required": "true"  
  12.         },  
  13.         {  
  14.             "fieldName": "age",  
  15.             "type": "simple",  
  16.             "required": "true"  
  17.         }  
  18.     ]  
  19. }  


推荐一个好的JSON在线解析工具:http://www.json.cn/

posted @ 2017-01-20 18:11  ding9587  阅读(1749)  评论(0编辑  收藏  举报