Languages
[Edit]
EN

JavaScript - how to format json?

7 points
Created by:
Imaan-Morin
1009

In this article, we're going to have a look at how to write own function to prettify json.

Quick solution:

 

Custom implementation

Edit

To format json we need to do 2 steps:

  1. parse JSON to object,
  2. render object back to JSON.

To write own object back to JSON renderer function we need to:

  • iterate over objects and arrays,
  • detect type of object,
  • escape unsafe characters like newlines, backslashes, double quote marks, etc.
  • join everything together using indents.

Practical example:

Note: undefined is not valid json token, this is the reasone why is not included in switch cases.

Alternative titles

  1. JavaScript - how to prettify json?
  2. JavaScript - prettify json logic
  3. JavaScript - custom prettify json logic
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - JSON

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join