Last Updated: November 24, 2019
·
12.39K
· 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.

Example:

>>> JSON.stringify({foo: 1, bar: 2, baz: [4,5,6]})  
'{"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": [
    4,
    5,
    6
  ]
}'

(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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside