JavaScript How to Convert Array to JSON String
JSON.stringify(yourArray) to convert an array to a JSON string in JavaScript.Examples
How to Think About It
JSON.stringify that takes any value, including arrays, and returns a JSON string representation.Algorithm
Code
const array = ["apple", "banana", "cherry"]; const jsonString = JSON.stringify(array); console.log(jsonString);
Dry Run
Let's trace converting ["apple", "banana", "cherry"] to JSON string.
Input array
["apple", "banana", "cherry"]
Convert using JSON.stringify
JSON.stringify(["apple", "banana", "cherry"])
Output JSON string
"[\"apple\",\"banana\",\"cherry\"]"
| Step | Action | Value |
|---|---|---|
| 1 | Input array | ["apple", "banana", "cherry"] |
| 2 | Call JSON.stringify | "[\"apple\",\"banana\",\"cherry\"]" |
| 3 | Print output | "[\"apple\",\"banana\",\"cherry\"]" |
Why This Works
Step 1: Why use JSON.stringify
The JSON.stringify method converts JavaScript values, including arrays, into a JSON-formatted string.
Step 2: How arrays are converted
Each element in the array is converted to its JSON representation and combined with commas inside square brackets.
Step 3: Result is a string
The output is a string that looks like JSON, which can be sent or stored easily.
Alternative Approaches
const array = [1, 2, 3]; let jsonString = '[' + array.map(item => '"' + item + '"').join(',') + ']'; console.log(jsonString);
import _ from 'lodash'; const array = [1, 2, 3]; const jsonString = JSON.stringify(array); console.log(jsonString);
Complexity: O(n) time, O(n) space
Time Complexity
The time depends on the number of elements in the array because each element must be processed and converted to a string.
Space Complexity
The output string size grows with the array size, so space is proportional to the input array length.
Which Approach is Fastest?
Using JSON.stringify is optimized and faster than manual string building.
| Approach | Time | Space | Best For |
|---|---|---|---|
| JSON.stringify | O(n) | O(n) | All array to JSON conversions |
| Manual string concatenation | O(n) | O(n) | Simple arrays but error-prone |
| Using libraries | O(n) | O(n) | Complex data manipulation before conversion |
JSON.stringify to safely convert arrays to JSON strings.