pretty-print JSON using JavaScript

后端 未结 24 1666
一向
一向 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 06:55

    Douglas Crockford's JSON in JavaScript library will pretty print JSON via the stringify method.

    You may also find the answers to this older question useful: How can I pretty-print JSON in (unix) shell script?

    0 讨论(0)
  • 2020-11-21 06:58

    Better way.

    Prettify JSON Array in Javascript

    JSON.stringify(jsonobj,null,'\t')
    
    0 讨论(0)
  • 2020-11-21 06:59

    You can use console.dir(), which is a shortcut for console.log(util.inspect()). (The only difference is that it bypasses any custom inspect() function defined on an object.)

    It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.

    const object = JSON.parse(jsonString)
    
    console.dir(object, {depth: null, colors: true})
    

    and for the command line:

    cat package.json | node -e "process.stdin.pipe(new stream.Writable({write: chunk => console.dir(JSON.parse(chunk), {depth: null, colors: true})}))"

    0 讨论(0)
  • 2020-11-21 07:00

    Here is a simple JSON format/color component written in React:

    const HighlightedJSON = ({ json }: Object) => {
      const highlightedJSON = jsonObj =>
        Object.keys(jsonObj).map(key => {
          const value = jsonObj[key];
          let valueType = typeof value;
          const isSimpleValue =
            ["string", "number", "boolean"].includes(valueType) || !value;
          if (isSimpleValue && valueType === "object") {
            valueType = "null";
          }
          return (
            <div key={key} className="line">
              <span className="key">{key}:</span>
              {isSimpleValue ? (
                <span className={valueType}>{`${value}`}</span>
              ) : (
                highlightedJSON(value)
              )}
            </div>
          );
        });
      return <div className="json">{highlightedJSON(json)}</div>;
    };
    

    See it working in this CodePen: https://codepen.io/benshope/pen/BxVpjo

    Hope that helps!

    0 讨论(0)
  • 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
        }
      }
    */
    
    0 讨论(0)
  • 2020-11-21 07:02

    The simplest way to display an object for debugging purposes:

    console.log("data",data) // lets you unfold the object manually
    

    If you want to display the object in the DOM, you should consider that it could contain strings that would be interpreted as HTML. Therefore, you need to do some escaping...

    var s = JSON.stringify(data,null,2) // format
    var e = new Option(s).innerHTML // escape
    document.body.insertAdjacentHTML('beforeend','<pre>'+e+'</pre>') // display
    
    0 讨论(0)
提交回复
热议问题