📅  最后修改于: 2023-12-03 15:16:58.886000             🧑  作者: Mango
Have you ever needed to convert a JavaScript object to a JSON string and make it readable with proper spacing, indentation, and line breaks? Look no further than the JSON.stringify
function with the space
parameter!
The JSON.stringify
function is used to convert a JavaScript object to a JSON string. By default, the resulting JSON string will be a continuous string with no line breaks or proper spacing.
const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString);
// Output: {"name":"John","age":30}
To make the resulting JSON string readable, the JSON.stringify
function allows for a space
parameter to be added. This parameter is a non-negative integer or string that sets the size of the space used for indentation. An integer sets the number of spaces used, while a string sets the characters used for indentation. For example,
const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj, null, 2);
console.log(jsonString);
// Output:
// {
// "name": "John",
// "age": 30
// }
In this example, the null
parameter is used for the replacer
parameter, which is not needed for basic object-to-JSON conversions. The 2
parameter is used for the space
parameter, indicating that two spaces should be used for indentation.
Using the JSON.stringify
function with the space
parameter is a powerful tool for converting JavaScript objects to readable JSON strings. With proper spacing, indentation, and line breaks, your code will be easier to read and debug.