JavaScript How to Convert Object to JSON String
JSON.stringify(yourObject) to convert a JavaScript object into a JSON string.Examples
How to Think About It
Algorithm
Code
const obj = { name: "Alice", age: 30 }; const jsonString = JSON.stringify(obj); console.log(jsonString);
Dry Run
Let's trace converting { name: "Alice", age: 30 } to JSON string.
Start with object
{ name: "Alice", age: 30 }
Call JSON.stringify
JSON.stringify({ name: "Alice", age: 30 })
Get JSON string
"{\"name\":\"Alice\",\"age\":30}"
| Step | Value |
|---|---|
| 1 | { name: "Alice", age: 30 } |
| 2 | JSON.stringify called |
| 3 | "{\"name\":\"Alice\",\"age\":30}" |
Why This Works
Step 1: Why use JSON.stringify
The JSON.stringify method converts an object into a string that follows JSON format, which is easy to send or save.
Step 2: How it works
It looks at each key and value in the object and creates a text version with quotes and commas as JSON requires.
Step 3: Result is a string
The output is a string, not an object, so you can store it or send it over the internet.
Alternative Approaches
const obj = { name: "Alice", age: 30 }; const jsonString = '{"name":"' + obj.name + '","age":' + obj.age + '}'; console.log(jsonString);
const obj = { name: "Alice", age: 30, password: "secret" }; const jsonString = JSON.stringify(obj, (key, value) => key === 'password' ? undefined : value); console.log(jsonString);
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the number of keys and values in the object, as each must be processed to create the JSON string.
Space Complexity
The space needed grows with the size of the object because the output is a new string representing the entire object.
Which Approach is Fastest?
Using JSON.stringify is the fastest and safest method compared to manual string building or custom replacers.
| Approach | Time | Space | Best For |
|---|---|---|---|
| JSON.stringify | O(n) | O(n) | All object sizes, safe and standard |
| Manual string building | O(n) | O(n) | Very simple objects, not recommended |
| JSON.stringify with replacer | O(n) | O(n) | Filtering keys during conversion |
JSON.stringify to safely convert objects to JSON strings without errors.toString() on an object instead of JSON.stringify, which does not produce valid JSON.