Home Web Front-end JS Tutorial Formatting and highlighting json strings using regular expressions_javascript skills

Formatting and highlighting json strings using regular expressions_javascript skills

May 16, 2016 pm 04:29 PM
json string format regular expression Highlight

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to format c drive with dos command How to format c drive with dos command Feb 19, 2024 pm 04:23 PM

DOS command is a command line tool used in Windows operating system, which can be used to perform various system management tasks and operations. One of the common tasks is to format the hard drive, including the C drive. Formatting the C drive is a relatively dangerous operation because it will erase all data on the C drive and reinitialize the file system. Before performing this operation, make sure you have backed up important files and have a clear understanding of the impact that formatting will have on your computer. The following is formatted in the DOS command line

Will formatting a laptop make it faster? Will formatting a laptop make it faster? Feb 12, 2024 pm 11:54 PM

Will formatting a laptop make it faster? If you want to format your Windows laptop but want to know if it will make it faster, this article will help you know the right answer to this question. Will formatting a laptop make it faster? There are many reasons why users format their Windows laptops. But the most common reason is slow performance or speed of your laptop. Formatting a laptop will completely delete all data stored on the C drive or the hard drive partition where Windows operating system is installed. Therefore, every user will think twice before taking this step, especially when it comes to the performance of the laptop. This article will help you understand whether formatting your laptop will speed it up. Formatting your laptop helps

Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) Revealed secrets of cell phone format recovery methods (mobile phone malfunction? Don't worry) May 04, 2024 pm 06:01 PM

Nowadays, we will inevitably encounter some problems such as being unable to turn on the phone or lagging, such as system crash, but during use, mobile phones have become an indispensable part of our lives. We are often at a loss, and sometimes, there are no solutions to these problems. To help you solve cell phone problems, this article will introduce you to some methods of cell phone format recovery and restore your phone to normal operation. Back up data - protect important information, such as photos and contacts, from being lost during the formatting process. Before formatting your phone, the first thing to consider is to back up important data and files on your phone. To ensure data security, or choose to transfer files to a cloud storage service, you can back it up by connecting to a computer. Use the system's built-in recovery function - simple

PHP regular expression validation: number format detection PHP regular expression validation: number format detection Mar 21, 2024 am 09:45 AM

PHP regular expression verification: Number format detection When writing PHP programs, it is often necessary to verify the data entered by the user. One of the common verifications is to check whether the data conforms to the specified number format. In PHP, you can use regular expressions to achieve this kind of validation. This article will introduce how to use PHP regular expressions to verify number formats and provide specific code examples. First, let’s look at common number format validation requirements: Integers: only contain numbers 0-9, can start with a plus or minus sign, and do not contain decimal points. floating point

How to validate email address in Golang using regular expression? How to validate email address in Golang using regular expression? May 31, 2024 pm 01:04 PM

To validate email addresses in Golang using regular expressions, follow these steps: Use regexp.MustCompile to create a regular expression pattern that matches valid email address formats. Use the MatchString function to check whether a string matches a pattern. This pattern covers most valid email address formats, including: Local usernames can contain letters, numbers, and special characters: !.#$%&'*+/=?^_{|}~-`Domain names must contain at least One letter, followed by letters, numbers, or hyphens. The top-level domain (TLD) cannot be longer than 63 characters.

PHP regular expressions: exact matching and exclusion of fuzzy inclusions PHP regular expressions: exact matching and exclusion of fuzzy inclusions Feb 28, 2024 pm 01:03 PM

PHP Regular Expressions: Exact Matching and Exclusion Fuzzy inclusion regular expressions are a powerful text matching tool that can help programmers perform efficient search, replacement and filtering when processing text. In PHP, regular expressions are also widely used in string processing and data matching. This article will focus on how to perform exact matching and exclude fuzzy inclusion operations in PHP, and will illustrate it with specific code examples. Exact match Exact match means matching only strings that meet the exact condition, not any variations or extra words.

What are the methods of html formatting? What are the methods of html formatting? Mar 08, 2024 am 09:53 AM

HTML formatting method: 1. Use online HTML formatting tools; 2. Use the HTML formatting shortcut keys that come with the code editor, such as Shift + Alt + F in Visual Studio Code; 3. Use plug-ins, such as Sublime Text HTML/CSS/JS Prettify plug-in; 4. Use command line tools, such as HTML Tidy; 5. Manual formatting according to coding standards and habits.

How to match timestamps using regular expressions in Go? How to match timestamps using regular expressions in Go? Jun 02, 2024 am 09:00 AM

In Go, you can use regular expressions to match timestamps: compile a regular expression string, such as the one used to match ISO8601 timestamps: ^\d{4}-\d{2}-\d{2}T \d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-][0-9]{2}:[0-9]{2})$ . Use the regexp.MatchString function to check if a string matches a regular expression.

See all articles