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.)
Written by Ben Combee
Related protips
1 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
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#