JSON string formatting

Source: Internet
Author: User

    var str = ' {' id ': ', ' ' name ': ' Zhang San ', ' data ': {' id2 ': ' name2 ': ' Zhang San ', ' data ': {' id3 ': ' Name3 ': ' Zhang San "}}," addr ":" Mars Base "} ';//newline symbol, space symbol var hh =" \ n ", var trimf ="; var trimF2 = ";//format display JSON data function formatjsontostr ( STR) {var html = ' {' + ' \ n '; var jsondata = eval (' (' + str + ') '); var jsonlength = Getjsonlength (jsondata); var i = 0;for (VA R key in Jsondata) {i++;html + = Formatdata (key, Jsondata[key]); if (jsonlength! = i) {html + = "," + "\ n";}} html + = "\ n" + '} '; return html;} Format data function Formatdata (key, currobject) {var html = '; var type = typeof (Currobject); if (type = = ' String ' | | type = = ' Nu Mber ') {html + = ' + key + ': ' + currobject + ' "';;} else if (type = = ' object ') {html + = ' + key + ': {' + ' \ n '; var jsonlength = Getjsonlength (currobject); var i = 0;for ( var currkey in Currobject) {I++;var Currdata = currobject[currkey];html + = Formatdata (Currkey, Currdata); if (jsonLength! = i) {html + = "," + "\ n";}} html + = "\ n" + "+ '} ';} return HTML;} Get JSON length Function Getjsonlength (jsondata) {var jsonlength = 0;for (var item in jsondata) {jsonlength++;} return jsonlength;} Alert (FORMATJSONTOSTR (str));

Format the images below



JSON string formatting

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.