pretty-print JSON using JavaScript

后端 未结 24 1680
一向
一向 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:14

    User Pumbaa80's answer is great if you have an object you want pretty printed. If you're starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first:

    var jsonString = '{"some":"json"}';
    var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);  
    

    This builds a JSON object from the string, and then converts it back to a string using JSON stringify's pretty print.

提交回复
热议问题