JSON parse vs JSON stringify in JavaScript: Key Differences and Usage
JSON.parse converts a JSON string into a JavaScript object, while JSON.stringify converts a JavaScript object into a JSON string. They are opposite operations used to handle data exchange between strings and objects.Quick Comparison
Here is a quick side-by-side comparison of JSON.parse and JSON.stringify in JavaScript.
| Aspect | JSON.parse | JSON.stringify |
|---|---|---|
| Purpose | Convert JSON string to JavaScript object | Convert JavaScript object to JSON string |
| Input Type | String (JSON format) | JavaScript object or value |
| Output Type | JavaScript object or value | String (JSON format) |
| Common Use | Read JSON data from text or network | Prepare data to send or store as JSON |
| Error Handling | Throws error if input is invalid JSON | Throws error if object contains unsupported types (e.g., functions, symbols) |
| Example | `'{"name":"John"}'` | `{ "name": "John" }` |
Key Differences
JSON.parse takes a string that is formatted as JSON and turns it into a JavaScript object or value. This is useful when you receive data as text, such as from a web server, and want to work with it in your code as objects or arrays.
On the other hand, JSON.stringify takes a JavaScript object or value and turns it into a JSON string. This is helpful when you want to send data over a network or save it as text, because JSON strings are easy to transmit and store.
While JSON.parse expects a valid JSON string and will throw an error if the string is malformed, JSON.stringify can throw errors if the object contains values that cannot be converted to JSON, like functions or symbols. They are complementary functions that convert data back and forth between string and object forms.
JSON.parse Code Example
const jsonString = '{"name":"Alice","age":25}'; const obj = JSON.parse(jsonString); console.log(obj.name); console.log(typeof obj);
JSON.stringify Equivalent
const obj = { name: "Alice", age: 25 }; const jsonString = JSON.stringify(obj); console.log(jsonString); console.log(typeof jsonString);
When to Use Which
Choose JSON.parse when you have JSON data as a string and want to convert it into a JavaScript object to access or manipulate its properties.
Choose JSON.stringify when you want to convert a JavaScript object into a JSON string to send it over a network, save it to a file, or store it in a text-based format.
In short, use JSON.parse to read JSON strings into objects, and use JSON.stringify to write objects into JSON strings.
Key Takeaways
JSON.parse converts JSON strings into JavaScript objects.JSON.stringify converts JavaScript objects into JSON strings.JSON.parse to read and work with JSON data as objects.JSON.stringify to prepare objects for storage or transmission as JSON.