pretty-print JSON using JavaScript

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

    Here is how you can print without using native function.

    function pretty(ob, lvl = 0) {
    
      let temp = [];
    
      if(typeof ob === "object"){
        for(let x in ob) {
          if(ob.hasOwnProperty(x)) {
            temp.push( getTabs(lvl+1) + x + ":" + pretty(ob[x], lvl+1) );
          }
        }
        return "{\n"+ temp.join(",\n") +"\n" + getTabs(lvl) + "}";
      }
      else {
        return ob;
      }
    
    }
    
    function getTabs(n) {
      let c = 0, res = "";
      while(c++ < n)
        res+="\t";
      return res;
    }
    
    let obj = {a: {b: 2}, x: {y: 3}};
    console.log(pretty(obj));
    
    /*
      {
        a: {
          b: 2
        },
        x: {
          y: 3
        }
      }
    */
    

提交回复
热议问题