pretty-print JSON using JavaScript

后端 未结 24 1665
一向
一向 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

    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','
    '+e+'
    ') // display

提交回复
热议问题