Tips for optimizing JSON strings using regular expressions _ javascript skills

Source: Internet
Author: User
This article mainly introduces the skills of regular expressions to optimize JSON strings. For more information, see json strings. Sometimes the information returned by some background interfaces is in string format, poor readability. In this case, it would be much better to have a method that can be formatted and highlighted to display json strings. 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.

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 ).

// Add a newline reg =/([\{\}])/g; json = json before and after braces. replace (reg, '\ r \ n $1 \ r \ n'); // Add a line feed before and after brackets reg =/([\ [\])/g; json = json. replace (reg, '\ r \ n $1 \ r \ n'); // Add a line feed reg =/(\,)/g after a comma; 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.

// Remove unnecessary line breaks reg =/(\ r \ n)/g; json = json. replace (reg, '\ r \ n'); // remove reg =/\ r \ n \,/g; json = json from the line feed before the comma. replace (reg, ','); // indent reg before colon = // \:/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.

$.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.

// Here {, [the indentation level is increased by 1,}, and], the indentation level is reduced by 1, and 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 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.

. 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 to highlight 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

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 brackets reg =/([\ [\])/g; json = json. replace (reg, '\ r \ n $1 \ r \ n'); // Add a line feed reg =/(\,)/g after a comma; json = json. replace (reg, '$1 \ r \ n'); // Remove extra line breaks reg =/(\ r \ n)/g; json = json. replace (reg, '\ r \ n'); // remove reg =/\ r \ n \,/g from the line feed before the comma. json = j Son. replace (reg, ','); // indent reg before colon = // \:/g; json = json. replace (reg, ':'); // split the 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 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 to highlight 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

PS: Regular Expression replaces the numeric value of a json string

aa=aa.replaceAll("\"ccfsID\":\"[0-9]*\"", "\"ccfsID\":\""+id1+"\"");

Aa is a json string, for example:

{"items":[{"dishprice":30,"ccfsID":"","order.item.id":1,"zuofaid":"","zuofajiajia":0,"isTaoCan":false,"num":1,"price":30,"name":"","ID":"00000001","lsdishID":"","zuofaname":"","tzs":"","addTime":"2013-05-14"}],"deskId":"00000008"}
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.