zoukankan      html  css  js  c++  java
  • 校验字符串是否是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, " ")  
     
    [html] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. JSON.stringify(JSON.parse(json), null, 4)  



    PS: :代表缩进一个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/

  • 相关阅读:
    RJ-45与RJ-48的区别
    PCB设计铜铂厚度、线宽和电流关系
    PCB设计铜铂厚度、线宽和电流关系
    WiFi天线对PCB布局布线和结构的要求详解
    WiFi模块选型参考
    掩码是什么意思?
    计算机音频基础-PCM简介
    使用CSS2对页面中的文字添加彩色边框
    SQL Plus
    A Famous Music Composer
  • 原文地址:https://www.cnblogs.com/muliu/p/6323581.html
Copyright © 2011-2022 走看看