Last Updated: November 24, 2019
· unwiredben

Pretty-printing JSON from JavaScript

You probably already use JSON.stringify() as a quick way to look at a complex JavaScript object. However, did you know there was a third parameter that controls pretty-printing? If you use JSON.stringify(myObject, null, 2), you'll have line breaks added between items, and the formatter will use 2-space indentation to indicate levels of structure.


>>> JSON.stringify({foo: 1, bar: 2, baz: [4,5,6]})  

>>> JSON.stringify({foo: 1, bar: 2, baz: [4,5,6]}, null, 2)  
  "foo": 1,
  "bar": 2,
  "baz": [

(If you're curious, the second parameter I nulled out is used to specify a replacer function that can transform objects in the tree during output. This is useful when you've got data structures that have parts that can't be represented as a simple tree. See MDN for more details.)

1 Response
Add your response

Exactly what i was looking for . thanks :tada:

over 1 year ago ·