Use regular expressions to format and highlight json strings _ javascript skills

Source: Internet
Author: User
This article mainly introduces how to format and highlight json strings using regular expressions. It is very simple and practical. If you need it, you can refer to the json string, sometimes the information returned by some background interfaces is in string format and the readability is poor. In this case, it would be much better if there is a method that can be formatted and highlighted to display json strings, next let's take a look at the formatting and highlighting of json strings completed by a regular expression.

The first is to convert the input. If it is an object, it is converted to a standard json string. If it is not an object, it is first converted to an object (to prevent nonstandard strings ), then convert it to a json string. Json is the input.

The Code is as follows:


If (typeof json! = 'String '){
Json = JSON. stringify (json );
} Else {
Json = JSON. parse (json );
Json = JSON. stringify (json );
}

Mark the string after the canonicalized data.

There are several places to add tags, including braces, Parentheses, and commas, here I am using a line feed \ n (in this way, the test time in the command line will be better ).

The Code is as follows:


// Add a line feed before and after braces
Reg =/([\ {\}])/g;
Json = json. replace (reg, '\ r \ n $1 \ r \ n ');
// Add a line feed before and after parentheses
Reg =/([\ [\])/g;
Json = json. replace (reg, '\ r \ n $1 \ r \ n ');
// Add a line feed after a comma
Reg =/(\,)/g;
Json = json. replace (reg, '$1 \ r \ n ');

After adding a tag, We need to optimize it to remove unnecessary line breaks and line breaks before commas. This is done to avoid wasting loop processing when splitting empty strings, add a space after the colon to make it look more beautiful.

The Code is as follows:


// Remove unnecessary line breaks
Reg =/(\ r \ n)/g;
Json = json. replace (reg, '\ r \ n ');
// Remove the line break before the comma
Reg =/\ r \ n \,/g;
Json = json. replace (reg ,',');
// Indent before the colon
Reg =/\:/g;
Json = json. replace (reg ,':');

The next step is to further process the initially processed string. I will add the logic to the function (index, node) {} to process each Split unit, including indent and beautification formats.

The Code is as follows:


$. Each (json. split ('\ r \ n'), function (index, node ){});

First, let's talk about indentation. The indentation method is very simple. The indentation increases by 1 when the {or [symbol is used, and the indentation decreases by 1 when the} or] symbol is used. Otherwise, the indentation remains unchanged.

The Code is as follows:


// Here {, [the indentation level is increased by 1,}, and], the indentation level is reduced by 1, and the indentation level remains unchanged when not met
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 completed, you should beautify the highlighted code. here you need to use several css rules. We can see that regular expressions are used to judge when the Split unit is highlighted, if the matching braces are marked as the object class, the brackets are marked as the array class, the attribute name, and the attribute value, add these css rules at one time, and splice them after adding them.

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

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 ");

Finally, let's take a look at the complete method code (here I use the jquery Class Library) and the test address:

To beautify jsonstr, you can use APP. format (jsonstr) and directly output it

Label to see the effect, 

Below is a test address, http://iforever.sinaapp.com/can go in and try it, look at the complete source code

The Code is as follows:


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 a line feed before and after braces
Reg =/([\ {\}])/g;
Json = json. replace (reg, '\ r \ n $1 \ r \ n ');
// Add a line feed before and after parentheses
Reg =/([\ [\])/g;
Json = json. replace (reg, '\ r \ n $1 \ r \ n ');
// Add a line feed after a comma
Reg =/(\,)/g;
Json = json. replace (reg, '$1 \ r \ n ');
// Remove unnecessary line breaks
Reg =/(\ r \ n)/g;
Json = json. replace (reg, '\ r \ n ');
// Remove the line break before the comma
Reg =/\ r \ n \,/g;
Json = json. replace (reg ,',');
// Indent before the colon
Reg =/\:/g;
Json = json. replace (reg ,':');
// Split json according to the line feed and process each small block
$. Each (json. split ('\ r \ n'), function (index, node ){
Var I = 0,
Indent = 0,
Padding = '';
// Here {, [the indentation level is increased by 1,}, and], the indentation level is reduced by 1, and the indentation level remains unchanged when not met
If (node. match (/\ {$/) | node. match (/\ [$ /)){
Indent = 1;
} Else if (node. match (/\}/) | node. match (/\]/) {
If (pad! = 0 ){
Pad-= 1;
}
} Else {
Indent = 0;
}
// Padding stores the actual indentation
For (I = 0; I <pad; I ++ ){
Padding + = PADDING;
}
// 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 ");
Result + = padding + node +'
';
Pad + = indent;
});
Return result;
};
Return {
"Format": format,
};
}();
Script

How about whether the json string is beautiful? It is super practical. Of course, such a good stuff cannot be exclusive. We recommend it to our friends here.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.