Format and highlight json strings using regular expressions

  • 2020-03-30 04:27:22
  • OfStack

Json strings are useful, and sometimes some background interfaces return information in a string format that is not readable. It would be nice to have a way to format and highlight json strings

First, the input is converted to a canonical json string if it is an object. When it is not an object, the string is converted to an object (in case of non-canonical strings), and then to a json string again. Json is the input.


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

After the specification of the data to mark the string, for the following segmentation, recombination

There are a few places to add markup, including before and after curly braces, before and after curly braces, and after commas, and I'm using newline \r\n (so it looks better when tested from the command line).


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

After you've added the tag, you do some optimizations: you get rid of the extra line breaks, you get rid of the line breaks in front of commas, you do this to avoid wasting a loop on empty strings, and you end up with a space after the colon, which looks nice.


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

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


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

First of all, indentation, indentation method is very simple, encounter {, [symbol indentation increased by 1,},] symbol indentation reduced by 1, otherwise the amount of indentation is the same.


//Here, when {, [indentation level + 1, when},] indentation level minus 1, did not meet 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 completing the indentation on the beautification highlighting code, want to use a few CSS rules here, you can see below, the segmentation unit when the highlighted here with regular judge, if the match to brace for the object class, the brace marking for an array class, attribute name, attribute values, one of these CSS rules to add, add after pieced together.


.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, let's look at the complete method code (I used the jquery class library here), and the test address:

To beautify the jsonstr, app. format(jsonstr), output directly to < Pre> < / pre> You can see it in the label,

Here is a test address, (link: http://iforever.sinaapp.com/) can go in to try and see the complete 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 a newline
before and after the braces             reg = /([{}])/g;
            json = json.replace(reg, 'rn$1rn');
            //Add a newline
before and after the brackets             reg = /([[]])/g;
            json = json.replace(reg, 'rn$1rn');
            //After the comma, add a newline
            reg = /(,)/g;
            json = json.replace(reg, '$1rn');
            //Remove redundant newline
            reg = /(rnrn)/g;
            json = json.replace(reg, 'rn');
            //Remove
from the newline before the comma             reg = /rn,/g;
            json = json.replace(reg, ',');
            //
before the colon             reg = /:/g;
            json = json.replace(reg, ': ');
            //Json is shred by newline and then each small block
is processed             $.each(json.split('rn'), function(index, node) {
                var i = 0,
                    indent = 0,
                    padding = '';
                //Here, when {, [indentation level + 1, when},] indentation level minus 1, did not meet 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;
                }
                   //Padding holds 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 it, super practical, such a good thing, of course, not exclusive, here is recommended to friends.


Related articles: