I made a JSON format tool, and the pro-test can be used

Source: Internet
Author: User

Essay background: After requesting data from the back, we often get a bunch of JSON format. At this point, the program apes often use some of the online JSON formatting tools or tools similar to notepadd++ to convert them. Today, I smoothed the idea of smoothing, wrote a small plugin to format the JSON data. Recorded here.

1. Deploy a blank div on the page to enter JSON data into it for easy conversion.

The HTML code is as follows:

<div class= "FlexBox" >            <div id= "Data2" contenteditable= "true" style= "height:600px;flex:8;overflow-y: Scroll "></div>            <button style=" flex:1 "id=" JSONFORMAT2 ">json format </button>        </div >

Note: Setting the div's Contenteditable property value to True allows for a div to become editable. (I've always thought that only the input family or textarea can edit ...)

Page is as follows:

2. The next step is to use the JS code to traverse the JSON object for formatting.

My idea is that the JSON object is undoubtedly a key-value pair (key-value), we can first walk through each of the JSON object's properties (key), determine the type of the property value (value), if it is an object, a method is processed, if it is a non-object, then directly show , we would like to define the above method as MoreInfo, if the type of traversal to a value is an array (array), then we recursively, continue to loop calls the MoreInfo method until each of the smallest units of the key value pair out.

So how do we get each key-value pair in a single line? Here I'm using the <p> tag, and wrap the key-value in the <p> tab. Recursive this together, say very around, need to think clear, consider each situation, and then the corresponding operation.

Said my idea, followed by the JS code section:

var newele= ';        $ (' #jsonFormat2 '). On (' click ', Function () {            var resdata2=json.parse ($ (' #data2 '). text ());            $ (' #data2 '). html (');            Newele= ";            For (var item in resData2) {                if (typeof (Resdata2[item])! = ' object ' | | resdata2[item]==null) {                    newele+= ' <p> <span class= "title" > ' +item+ ' </span>: ' +resdata2[item]+ ',</p> ';                } else{                    moreinfo (Resdata2[item],item);                }            }            $ (' #data2 '). HTML (Newele);        })

In the above code: Newele is the final format of the JSON data structure we will show, set the button click event, one time to judge processing.

Next is the more critical function MoreInfo:

function MoreInfo (Obj,item) {if (obj instanceof Array{newele+= ' <p><span class= ' title ' > ' +item+ ': [' + ' </span> ' + ' </p> '; for (Var i=0;i<obj.length;i++) {if (typeof (Obj[i])! = ' object ') {newele+= ' &LT;P&G                    T;<span class= "title" > ' +obj[i]+ ',</span></p> '; }else{moreinfo (Obj[i], ')}} newele+= ' <p>&            Lt;span class= "title" > ' + ' + ' + ' </span> ' + ',</p> '; }else if (typeof (obj) = = ' object ' &&! ( obj instanceof Array) {newele+= ' <p><span class= ' title ' > ' +item+ ' {' + ' </span> ' + ' </p> '                ; For (var item in obj) {if (typeof (Obj[item])! = ' object ' | | obj[item]==null) {Newele                    + = ' <p><span class= ' title ' > ' +item+ ' </span>:     ' +obj[item]+ ',</p> '; }else{MoreInfo (obj[iTem],item)}} newele+= ' <p><span class= ' title ' > ' + '}, ' + ' </s            Pan> ' + ' </p> ';            }else{newele+= ' <p><span class= ' title ' > ' +obj+ ' </span> ' + ',</p> '; }        }

Tips: Although there is no array in the native object of JavaScript, that is, through typeof () to an array, even if it is typeof (["1", "2"]), the object is returned. But through obj instanceof Array can determine whether an object is an array type.

3. The final effect is as follows:

Too much content will not be all.

Summary: At first I wrote in the company for about 40 minutes, but after entering into the function of moreinfo, the second layer of the JSON object can not be removed from the key values, go home to clear the idea after the solution. There are two reasons:

1. The second layer of the object is an array of arrays, for the array this block before processing, the elements of the array may be an object, it may be just a string, and the inside of the object may have objects as well as String ..., so recursive loop

2. When calling the MoreInfo function, I started by passing the Newele as a parameter and returning it through the return method. But in fact failed, go home to clear the idea after, just fine:

function MoreInfo (Obj,item,ele) {if (obj instanceof Array) {ele+= ' <p><span class= ' title ' > ' +it            em+ ': [' + ' </span> ' + ' </p> '; for (Var i=0;i<obj.length;i++) {if (typeof (Obj[i])! = ' object ') {ele+= ' <p><span                class= "title" > ' +obj[i]+ ',</span></p> '; }else{moreinfo (Obj[i], ')}} ele+= ' <p><span class= ' titl        E "> ' + '] ' + ' </span> ' + ',</p> '; }else if (typeof (obj) = = ' object ' &&! (            obj instanceof Array) {ele+= ' <p><span class= ' title ' > ' +item+ ' {' + ' </span> ' + ' </p> '; For (var item in obj) {if (typeof (Obj[item])! = ' object ' | | obj[item]==null) {ele+= ' &                Lt;p><span class= "title" > ' +item+ ' </span>:     ' +obj[item]+ ',</p> ';      }else{MoreInfo (Obj[item],item)          }} ele+= ' <p><span class= ' title ' > ' + '}, ' + ' </span> ' + ' </p> ';        }else{ele+= ' <p><span class= ' title ' > ' +obj+ ' </span> ' + ',</p> '; }    }

When MoreInfo is called again inside the MoreInfo function, Ele is not passed out, causing the newele to change.

Of course, this small plug-in is flawed, for example, when judging the comma at the end of the object, it needs to be optimized.

PS: Today I think enough detailed explanation of the amount of blog Park review of the small, you will be my blog out of the blog home page, it is not justified it ~ 0 0

I made a JSON format tool, and the pro-test can be used

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.