-->

JavaScript - JSON Part 3: Stringifying JSON (Convert Object to JSON String)

What is JSON Stringifying?

Stringifying JSON means converting a JavaScript object into a JSON string using JSON.stringify(). This is useful when sending data to APIs.

Example 3: Converting an Object to a JSON String

const product = { id: 101, name: "Laptop", price: 799.99 };

const jsonString = JSON.stringify(product);

console.log(jsonString);

// Output: {"id":101,"name":"Laptop","price":799.99}

Explanation:

The JSON.stringify() function converts the JavaScript object into a JSON string.

The output is a valid JSON string, ready for transmission over a network.

Example 4: Formatting JSON Output

For better readability, add spaces:

console.log(JSON.stringify(product, null, 4)); 

This formats JSON with indentation:

{

    "id": 101,

    "name": "Laptop",

    "price": 799.99

}

Useful for debugging or displaying JSON nicely.