pretty-print JSON using JavaScript

后端 未结 24 2201
一向
一向 2020-11-21 06:45

How can I display JSON in an easy-to-read (for human readers) format? I\'m looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

24条回答
  •  耶瑟儿~
    2020-11-21 07:08

    var jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07",  "postalCode": "75007", "countryCode": "FRA",  "countryLabel": "France" };
    
    document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);
    

    In case of displaying in HTML, you should to add a balise

    document.getElementById("result-after").innerHTML = "
    "+JSON.stringify(jsonObj,undefined, 2) +"
    "

    Example:

    var jsonObj = {"streetLabel": "Avenue Anatole France", "city": "Paris 07",  "postalCode": "75007", "countryCode": "FRA",  "countryLabel": "France" };
    
    document.getElementById("result-before").innerHTML = JSON.stringify(jsonObj);
    
    document.getElementById("result-after").innerHTML = "
    "+JSON.stringify(jsonObj,undefined, 2) +"
    "
    div { float:left; clear:both; margin: 1em 0; }

提交回复
热议问题