JavaScript How to Convert JSON to Object Easily
Use
JSON.parse(jsonString) to convert a JSON string into a JavaScript object.Examples
Input"{\"name\":\"Alice\",\"age\":25}"
Output{"name":"Alice","age":25}
Input"{\"isStudent\":true,\"scores\":[90,85,88]}"
Output{"isStudent":true,"scores":[90,85,88]}
Input"{}"
Output{}
How to Think About It
To convert JSON to an object, think of JSON as a text format that looks like JavaScript objects but is actually a string. You need to turn this string back into a real object that your code can use. The built-in
JSON.parse method reads the string and creates the matching object.Algorithm
1
Get the JSON string input.2
Use the JSON.parse method to read the string.3
Return the resulting JavaScript object.Code
javascript
const jsonString = '{"name":"Alice","age":25}'; const obj = JSON.parse(jsonString); console.log(obj); console.log(obj.name);
Output
{ name: 'Alice', age: 25 }
Alice
Dry Run
Let's trace converting '{"name":"Alice","age":25}' to an object.
1
Input JSON string
{"name":"Alice","age":25}
2
Parse JSON string
JSON.parse('{"name":"Alice","age":25}')
3
Output JavaScript object
{ name: 'Alice', age: 25 }
| Step | Action | Value |
|---|---|---|
| 1 | Input JSON string | {"name":"Alice","age":25} |
| 2 | Call JSON.parse | Object { name: 'Alice', age: 25 } |
| 3 | Use object | obj.name = 'Alice' |
Why This Works
Step 1: JSON is a string format
The input is a string that looks like an object but is plain text.
Step 2: JSON.parse converts string to object
The JSON.parse method reads the string and builds a real JavaScript object.
Step 3: Result is usable JavaScript object
After parsing, you can access properties like obj.name just like any object.
Alternative Approaches
Using eval (not recommended)
javascript
const jsonString = '{"name":"Alice","age":25}'; const obj = eval('(' + jsonString + ')'); console.log(obj);
This works but is unsafe and can run harmful code, so avoid it.
Using a try-catch block with JSON.parse
javascript
const jsonString = '{"name":"Alice","age":25}'; let obj; try { obj = JSON.parse(jsonString); } catch (e) { console.error('Invalid JSON'); } console.log(obj);
This safely handles errors if the JSON string is invalid.
Complexity: O(n) time, O(n) space
Time Complexity
Parsing the JSON string requires reading each character once, so it takes linear time relative to the string length.
Space Complexity
The method creates a new object in memory proportional to the size of the JSON string.
Which Approach is Fastest?
JSON.parse is optimized and safe, making it the best choice over alternatives like eval.
| Approach | Time | Space | Best For |
|---|---|---|---|
| JSON.parse | O(n) | O(n) | Safe and standard JSON parsing |
| eval | O(n) | O(n) | Unsafe, avoid for JSON parsing |
| JSON.parse with try-catch | O(n) | O(n) | Safe parsing with error handling |
Always use
JSON.parse to safely convert JSON strings to objects.Trying to use JSON strings directly as objects without parsing causes errors.