Formatting and highlighting JSON strings using regular expressions
JSON strings are useful, and sometimes the information returned by some backend interfaces is in string format and is very readable, so if there is a way to format and highlight the JSON string, then let's look at the formatting and highlighting of a regular expression-completed JSON
The first is the conversion of the input, if the object is converted to a canonical JSON string, not an object, first convert the string to an object (to prevent the non-canonical string), and then again into a JSON string. where JSON is input.
if (typeof json!== ' string ') { JSON = json.stringify (JSON);} else { JSON = Json.parse (JSON); JSON = json.stringify (JSON);}
After the specification is finished, the string is marked for later segmentation, re-grouping
Here are a few places to add tags, including curly braces, parentheses, and trailing commas to add tags, and I'm using the line break \ r \ n (so the effect looks good when you test under the command line).
Add line-Wrap reg =/([\{\}]) before and after the curly brace/g;json = Json.replace (Reg, ' \r\n$1\r\n ');//Add newline before and after brackets =/([\[\]])/g;json = Json.replace (r eg, ' \r\n$1\r\n ');//comma followed by add newline reg =/(\,)/g;json = Json.replace (Reg, ' $1\r\n ');
After adding the completion tag to do some optimization processing, remove the extra line, remove the comma before the line break, so that in order to avoid the empty string wasted a loop processing, and finally add a space after the colon, looks more beautiful.
Remove the extra line-Break Reg =/(\r\n\r\n)/g;json = Json.replace (Reg, ' \ r \ n ');//The line break in front of the comma minus reg =/\r\n\,/g;json = Json.replace (Reg, ', '); /colon in front of indent reg =/\:/g;json = Json.replace (Reg, ': ');
The next step is to deal with this preliminary string, and I'll add logic to the function (Index, node) {} to process each slice, including indentation and landscaping.
$.each (Json.split (' \ r \ n '), function (Index, node) {});
First of all, the indentation, indentation method is very simple, encountered {, [sign the indentation increased by 1, encountered},] the symbol is reduced by 1 indent, otherwise the indentation is unchanged.
Here {, [when the indentation level plus 1, encountered},] the indentation level minus 1, did not encounter the indentation level unchanged if (Node.match (/\{$/) | | node.match (/\[$/)) { indent = 1;} else if ( Node.match (/\}/) | | Node.match (/\]/)) { if (pad!== 0) { pad-= 1; }} else { indent = 0;}
After the indentation is done to beautify the highlighting code, here to use a few CSS rules, the following can be seen, the segmentation unit is highlighted here with the regular judgment, if the match to the curly braces marked as the object class, the brackets are marked as an array class, the property name, the property value, Add these CSS rules at once, and add them together once you're done.
. Objectbrace{color: #00AA00; font-weight:bold;}. Arraybrace{color: #0033FF; font-weight:bold;}. Propertyname{color: #CC0000; font-weight:bold;}. String{color: #007777;}. Number{color: #AA00AA;}. Comma{color: #000000; font-weight:bold;}
Add code highlighting node = Node.replace (/([\{\}])/g, "<span class= ' objectbrace ' >$1</span>"), node = Node.replace (/([\ \ [\]]) /g, "<span class= ' arraybrace ' >$1</span>"); node = node.replace (/(\ ". *\") (\:) (. *) (\,)?/g, "<span class= ' PropertyName ' >$1</span>$2$3$4 '); node = Node.replace (/\ "([^"]*) \ "(\,)? $/g," <span class= ' String ' >\ " $1\ "</span><span class= ' Comma ' >$2</span>"); node = Node.replace (/(-?\d+) (\,)? $/g, "<span class= ' Number ' >$1</span><span class= ' Comma ' >$2</span> ');
Finally we look at the Complete method code (I used the jquery class library here), and the test address:
To beautify the jsonstr, so that you can App.format (JSONSTR), direct output to the <pre></pre> label can see the effect,
Here is a test address, http://iforever.sinaapp.com/can go in and try to see the full source code
<script> var app=function () {var format=function (JSON) {var reg=null, result= '; Pad=0, padding= '; if (typeof json!== ' string ') {JSON = json.stringify (JSON); } else {json = Json.parse (JSON); JSON = json.stringify (JSON); }//Add line-wrap reg =/([\{\}]) before and after the curly braces/g; JSON = Json.replace (Reg, ' \r\n$1\r\n '); Add newline reg =/([\[\]]) before and after the brackets/g; JSON = Json.replace (Reg, ' \r\n$1\r\n '); Add a newline after the comma reg =/(\,)/g; JSON = Json.replace (Reg, ' $1\r\n '); Remove the extra line Reg =/(\r\n\r\n)/g; JSON = Json.replace (Reg, ' \ r \ n '); The line break before the comma removes reg =/\r\n\,/g; JSON = Json.replace (Reg, ', '); Indent reg =/\:/g in front of colon; JSON = Json.replace (Reg, ': '); The JSON is sliced by line break and then processed by eachSmall Block $.each (json.split (' \ r \ n '), function (Index, node) {var i = 0, indent = 0, padding = "; Here {, [when the indent level plus 1, encountered},] the indentation level minus 1, did not encounter the indentation level unchanged if (Node.match (/\{$/) | | node.match (/\[$/)) {i Ndent = 1; } else if (Node.match (/\}/) | | Node.match (/\]/)) {if (Pad!== 0) {pad-= 1; }} else {indent = 0; }//padding Save the actual indentation for (i = 0; i < pad; i++) {padding + = padding; }//Add code highlighting node = Node.replace (/([\{\}])/g, "<span class= ' Objectbrace ' >$ 1</span> "); node = node.replace (/([\[\]])/g, "<span class= ' arraybrace ' >$1</span>"); node = node.replace (/(\ ". *\") (\:) (. *) (\,)?/g, "<span class= ' PropertyName ' >$1</span>$2$3$4 "); node = Node.replace (/\ "([^"]*) \ "(\,)? $/g," <span class= ' String ' >\ "$1\" </span><span class= ' Comma ' > $2</span> "); node = node.replace (/(-?\d+) (\,)? $/g, "<span class= ' number ' >$1</span><span class= ' Comma ' >$2</ Span> "); Result + = padding + node + ' <br> '; Pad + = indent; }); return result; }; return {"format": Format,}; } ();</script>
How, JSON string is not beautiful a lot of, super practical bar, such a good thing, of course, not exclusive, here is recommended to small friends.
Reference Source:
Formatting and highlighting JSON strings using regular expressions
Http://www.lai18.com/content/351722.html
Extended Reading
JavaScript Regular Expression Series technical articles organize collections
IgnoreCase properties in 1JavaScript regular expressions use detailed
2 in-depth use of the global property in JavaScript regular expressions
3 Introduction to the use of the test () method in a regular expression of javascript
4 using the Exec () method in a regular expression in JavaScript
Application of the Multiline attribute of 5JavaScript regular expression
6 A brief introduction to the use of regular expressions in JavaScript
7jQuery regular expression to get the name of the uploaded file
8 "JavaScript" uses regular expressions to check if the input box is a URL
9Javascript Regular expressions implement to add thousands separators to numbers
Guidelines for using regular expressions in 10javascript
11javascript using regular expressions to implement characters that are removed after a space
12 debugging JavaScript problems encountered in a regular expression
13jquery How to use regular expressions to verify an e-mail address
Example of search () usage for 14javascript regular expressions
15javascript Regular Expressions replace phone numbers with replace ()
Replacing regular expressions with DOM operations in 16jQuery
17javascript using regular expressions to detect IP addresses
18 using regular expressions to format and highlight JSON strings
19Js Regular Expression Knowledge Summary
20 Example Analysis JS and C # use regular expressions to match a label
21 Regular expressions in JavaScript applications
22 several instances of regular expressions in JavaScript
23 using js+ Regular expressions to add links to keywords
24 full validation of forms with regular expressions and JavaScript
25javascript Regular Expression validation
26javascript Learning Notes (eight) regular expressions
27JS Apply Regular Expression conversion case example
28javascript Regular expression parameter/g usage guide for/I and/GI
29JavaScript using regular expressions to remove "-" from a date
30 Delete a regular expression for comment statements in JavaScript
31JavaScript using regular expressions to remove dates from-
32node.js Regular Expressions get code instances for all links in a Web page
Examples of regular expressions commonly used in 33javascript
34JS searching and replacing instances of strings using the Replace () method and regular expressions
Concise summary of regular expressions in 35JavaScript
36JavaScript Forms verify phone numbers with regular expressions
37JavaScript implementing form validation phone numbers with regular expressions
Two methods of 38js dynamic splicing regular expression
39 implementing form validation with regular expressions is Chinese
Description of the difference between Test,exec,match methods in 40js regular expressions
41JS Regular expression Validation numeric code
42 using JS Regular expression to verify the phone number, email address, zip code
43JS Verify phone number and phone support +86 regular expression
Regular Expressions in 44JavaScript
45 summary of several methods of special symbols and regular expressions in regular expressions (Replace,test,search)
46 Common JavaScript Validation Regular expression rollup
47 Replace the image address with the regular expression img tag
48javascipt matching single-line and multiline-comment regular expressions
49js validating forms with regular expressions (more complete resources)
50JS Regular Expressions Get a detailed description of how to group content
51JS Regular Expression Daquan (detailed and practical collation)
52js How to convert a string to a regular expression
53JS Common Regular Expression summary
54js writing trim () function and the use of regular expressions
Summary of regular expressions for 55jQuery test time format
56JQuery numeric type validation regular expression
Regular expressions commonly used in 57jQuery
58jquery MACTH Regular Expression instance
Regular expressions commonly seen in 59jquery
60Jquery Validate Regular Expression Practical validation code Daquan
Use of 61JS Regular expressions
62 How to use JavaScript regular expressions to format XML content
6,330-minute Introductory Regular Expression Basics tutorial
64 regular expression with JS easy to handle JSON text convenient and old ancient
65js Replace Regular expression application case explanation
66 Useful JS Regular Expressions (mobile phone number/IP regular/ZIP/phone, etc.)
67javascript Regular expression correlation should be introduced
68JavaScript Advanced Programming (3rd Edition) Learning Note JS Regular expression
69Java Regular Expression Learning summary and some small examples
70js Limit text box to enter only numbers (regular expressions)
71JS Regular Expressions for judging the number \ Letter \ Chinese (instance)
72javascript Learning Notes (11) Introduction to Regular expressions
73JS Regular Expressions
74 get the data from the server regular expressions for using JS to remove spaces
75javascript Advanced article 1 regular expressions, cookie management, UserData
76jQuery Source Code Analysis-02 Regular Expressions RegExp Common regular expressions
77JavaScript Regular Expression Browser differences
78 Common JavaScript Regular expressions
Description of regular Expressions in 79jquery
80PHP regular expression that matches consecutive numbers or letters
The global matching pattern analysis of the 81Javascript Express expression
82javascript Learning Notes (v) Regular expressions
83 Regular Summary: regular expressions in JavaScript
84js Replace function function, solve with regular expression, JS Replace All
function of parameter G (global) in 85javascript regular expressions
86js Various validation text box input format (regular expression)
87javascript Regular Expression (i)
88 notation of regular expressions matching any character
89javascript Regular expression trigger function for advanced substitution
90JavaScript Learning Notes (14) Regular expressions
Implementation of regular expressions using array caches under 91javascript
92Mootools 1.2 Tutorial Regular expressions
93javascript gets the regular expression within the first slash in the address of the linked file
94 using regular expressions to dynamically create/Add CSS style script-compatible IE Firefox
The performance of JS regular expression in 95trim prototype function
96 Regular expressions determine if Chinese and full-width characters are present and determine the length of the string containing the Chinese character
97javascript Replace method and regular expression
98JS Replace method and regular expression in combination with application
99 a good example of regular expression learning regular expressions used in the Forum repost tool
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Formatting and highlighting JSON strings using regular expressions