Home  >  Article  >  Web Front-end  >  Formatting and highlighting json strings using regular expressions_javascript skills

Formatting and highlighting json strings using regular expressions_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:29:321594browse

Json strings are very useful. Sometimes the information returned by some background interfaces is in string format and has poor readability. At this time, it would be much better if there was a method that could format and highlight the json string. Let’s take a look at the formatting and highlighting of a json string completed by a regular expression

The first step is to convert the input. If it is an object, it is converted into a standardized json string. If it is not an object, the string is first converted into an object (to prevent non-standard strings), and then converted into a json string again. Where json is the input.

Copy code The code is as follows:

if (typeof json !== 'string') {
json = JSON.stringify(json);
} else {
json = JSON.parse(json);
json = JSON.stringify(json);
}

After standardizing the data, mark the string for subsequent segmentation and recombination

There are several places where you need to add tags, including brackets, brackets, and commas. I use line breaks here. n (this way the effect will look better when tested under the command line).

Copy code The code is as follows:

//Add newlines before and after the braces
reg = /([{}])/g;
json = json.replace(reg, 'rn$1rn');
// Add line breaks before and after the square brackets
reg = /([[]])/g;
json = json.replace(reg, 'rn$1rn');
// Add a newline after the comma
reg = /(,)/g;
json = json.replace(reg, '$1rn');

After adding the completion mark, you need to do some optimization processing, remove the extra line breaks, and remove the line breaks before the comma. This is to avoid empty strings during segmentation and waste a loop. Finally, add a space after the colon. See Looks prettier.

Copy code The code is as follows:

//Remove redundant line breaks
reg = /(rnrn)/g;
json = json.replace(reg, 'rn');
// Remove the newline before the comma
reg = /rn,/g;
json = json.replace(reg, ',');
//Indent before colon
reg = /:/g;
json = json.replace(reg, ': ');

The next step is to further process this initially processed string. I will add logic to the function(index, node) {} function to process each segmentation unit, including indentation and beautifying formatting.

Copy code The code is as follows:

$.each(json.split('rn'), function(index, node) {});

First of all, let’s talk about indentation. The indentation method is very simple. When encountering {, [symbols, the indentation increases by 1, and when encountering }, ] symbols, the indentation decreases by 1. Otherwise, the indentation amount remains unchanged.

Copy code The code is as follows:

//When encountering {, [here, the indentation level increases by 1, when encountering }, ], the indentation level decreases by 1, and when not encountered, the indentation level remains unchanged
if (node.match(/{$/) || node.match(/[$/)) {
indent = 1;
} else if (node.match(/}/) || node.match(/]/)) {
If (pad !== 0) {
         pad -= 1;
}
} else {
indent = 0;
}

After completing the indentation, it is time to beautify the highlighted code. Several css rules are used here. As you can see below, when highlighting the segmented units, regular rules are used to judge. If it matches the large The brackets mark the object class, and the square brackets mark the array class, attribute name, and attribute value. Add these CSS rules at once, and then splice them together after the addition is completed.

Copy code The code is as follows:

.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;}

Copy code The code is as follows:

//Add code highlighting
node = node.replace(/([{}])/g,"$1");
node = node.replace(/([[]])/g,"$1");
node = node.replace(/(".*")(:)(.*)(,)?/g,"$1$2$3$4");
node = node.replace(/"([^"]*)"(,)?$/g,""$1"$2");
node = node.replace(/(-?d )(,)?$/g,"$1$2< /span>");

Finally let’s take a look at the complete method code (here I used the jquery class library), and the test address:

To beautify jsonstr, just use APP.format(jsonstr) and output it directly to the

 tag to see the effect, 

The following is a test address, http://iforever.sinaapp.com/ You can go in and try it out and see the complete source code

Copy code The code is as follows:

<script><br> var APP=function(){<br>       var format=function(json){<br>             var reg=null,<br>                   result='';<br>                  pad=0,<br>                    PADDING='                                                                        If (typeof json !== 'string') {<br>                    json = JSON.stringify(json);<br>               } else {<br>                   json = JSON.parse(json);<br>                    json = JSON.stringify(json);<br>             }<br>                                                       // Add newlines before and after the braces <br>             reg = /([{}])/g;<br>                json = json.replace(reg, 'rn$1rn');<br> // Add a change of the line before and after the central bracket <br>             reg = /([[]])/g;<br>                json = json.replace(reg, 'rn$1rn');<br>                                                                                                                                                                                                  // Add a newline after the comma <br>             reg = /(,)/g;<br>                json = json.replace(reg, '$1rn');<br> // Remove the excess change <br>           reg = /(rnrn)/g;<br>               json = json.replace(reg, 'rn');<br> //Remove the newline before the comma<br>              reg = /rn,/g;<br>                json = json.replace(reg, ',');<br> //Indent before colon <br>             reg = /:/g;<br>                json = json.replace(reg, ': ');<br>                            // Split json according to newlines and process each small piece <br>                  $.each(json.split('rn'), function(index, node) {<br>               var i = 0,<br> indent = 0,<br>                          padding = '';<br>                                       //Here, when {, [ is encountered, the indentation level is increased by 1, when }, ] is encountered, the indentation level is reduced by 1, and when not encountered, the indentation level remains unchanged <br> If (node.match(/{$/) || node.match(/[$/)) {<br> indent = 1;<br>                        } else if (node.match(/}/) || node.match(/]/)) {<br> If (pad !== 0) {<br>                            pad -= 1;<br>                  }<br>                      } else {<br> indent = 0;<br>                }<br>                    //padding保存实际的缩进<br>                 for (i = 0; i < pad; i ) {<br>                     padding = PADDING;<br>                 }<br>                 //添加代码高亮<br>                 node = node.replace(/([{}])/g,"<span class='ObjectBrace'>$1</span>");<br>                 node = node.replace(/([[]])/g,"<span class='ArrayBrace'>$1</span>");<br>                 node = node.replace(/(".*")(:)(.*)(,)?/g,"<span class='PropertyName'>$1</span>$2$3$4");<br>                 node = node.replace(/"([^"]*)"(,)?$/g,"<span class='String'>"$1"</span><span class='Comma'>$2</span>");<br>                 node = node.replace(/(-?d )(,)?$/g,"<span class='Number'>$1</span><span class='Comma'>$2</span>");<br>                 result = padding node '<br>';<br>                 pad = indent;<br>             });<br>             return result;<br>         };<br>         return {<br>             "format":format,<br>         };<br>     }();<br> </script>

怎么样,json字符串是不是美观了很多呢,超级实用吧,这么好的东东,当然不能独享,这里推荐给小伙伴们。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn