pretty-print JSON using JavaScript

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

    Here's user123444555621's awesome HTML one adapted for terminals. Handy for debugging Node scripts:

    function prettyJ(json) {
      if (typeof json !== 'string') {
        json = JSON.stringify(json, undefined, 2);
      }
      return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, 
        function (match) {
          let cls = "\x1b[36m";
          if (/^"/.test(match)) {
            if (/:$/.test(match)) {
              cls = "\x1b[34m";
            } else {
              cls = "\x1b[32m";
            }
          } else if (/true|false/.test(match)) {
            cls = "\x1b[35m"; 
          } else if (/null/.test(match)) {
            cls = "\x1b[31m";
          }
          return cls + match + "\x1b[0m";
        }
      );
    }
    

    Usage:

    // thing = any json OR string of json
    prettyJ(thing);
    

提交回复
热议问题