📜  json.stringify pretty - Javascript (1)

📅  最后修改于: 2023-12-03 14:43:34.895000             🧑  作者: Mango

JSON.stringify() pretty - Javascript

JSON.stringify() is a method in JavaScript that allows you to convert a JavaScript object or value to a JSON string. By default, the resulting JSON string is not formatted in a readable manner. However, with the use of the "pretty" parameter, JSON.stringify() can format the JSON string in a more readable way.

Syntax
JSON.stringify(obj, replacer, space)

The "obj" parameter is the JavaScript object or value that needs to be converted to a JSON string. The "replacer" parameter is an optional function or array that can be used to transform the resulting JSON string. The "space" parameter is also an optional parameter that specifies the number of spaces for the indentation of the resulting JSON string.

Example
const obj = {
    name: "John",
    age: 27,
    favorites: {
        color: "blue",
        number: 7
    }
}

const prettyJSON = JSON.stringify(obj, null, 4)
console.log(prettyJSON)

The above example will output the following JSON string in a pretty format:

{
    "name": "John",
    "age": 27,
    "favorites": {
        "color": "blue",
        "number": 7
    }
}

As you can see, the resulting JSON string is indented by 4 spaces for each level.

Conclusion

In summary, JSON.stringify() pretty can be used to convert a JavaScript object or value to a more readable JSON string format. By specifying the "space" parameter, the resulting JSON string can be indented to make it easier to read and understand.