JSON (JavaScript Object Notation) is a lightweight data-interchange format frequently used in web applications for transmitting data between servers and clients. Raw JSON data, especially complex objects, can be challenging to read. Fortunately, JavaScript offers built-in methods to enhance JSON readability and management.
Table of Contents
- Formatting JSON Objects with
JSON.stringify()
- Reformatting JSON Strings using
JSON.stringify()
andJSON.parse()
Formatting JSON Objects with JSON.stringify()
The JSON.stringify()
method is the primary tool for converting JavaScript objects into JSON strings. While it defaults to compact output, the optional space
parameter controls formatting. This parameter specifies the indentation level.
Consider this JavaScript object:
const myDataObject = {
name: "John Doe",
age: 30,
address: {
street: "123 Main St",
city: "Anytown",
zip: "12345"
},
skills: ["JavaScript", "HTML", "CSS"]
};
To format this into a readable JSON string, use JSON.stringify()
with the space
parameter:
const formattedJson = JSON.stringify(myDataObject, null, 2); // 2 spaces for indentation
console.log(formattedJson);
This produces:
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"zip": "12345"
},
"skills": [
"JavaScript",
"HTML",
"CSS"
]
}
The 2
in JSON.stringify(myDataObject, null, 2)
sets the indentation to 2 spaces. Adjust this value (e.g., 4, or “t” for tabs) to your preference. The null
is a placeholder for a replacer function (allowing for more advanced formatting options, discussed in more advanced tutorials).
Reformatting JSON Strings using JSON.stringify()
and JSON.parse()
For poorly formatted JSON strings (e.g., single-line), combine JSON.parse()
and JSON.stringify()
for reformatting.
Example of an unformatted JSON string:
const unformattedJson = '{"name":"Jane Doe","age":25,"city":"New York"}';
First, parse the string into a JavaScript object:
const jsonObject = JSON.parse(unformattedJson);
Then, format the object back into a JSON string using JSON.stringify()
:
const formattedJson = JSON.stringify(jsonObject, null, 4); // 4 spaces for indentation
console.log(formattedJson);
Result:
{
"name": "Jane Doe",
"age": 25,
"city": "New York"
}
This two-step process effectively cleans up poorly formatted JSON. Always handle potential JSON.parse()
errors (using a try...catch
block) to prevent unexpected application crashes.
In summary, JSON.stringify()
, with or without JSON.parse()
, offers a simple way to format JSON data in JavaScript, significantly improving code readability.