How to Parse JSON in JavaScript: Simple Guide
To parse JSON in JavaScript, use the
JSON.parse() method which converts a JSON string into a JavaScript object. This allows you to work with the data as normal JavaScript values.Syntax
The basic syntax to parse JSON is JSON.parse(jsonString). Here, jsonString is a string formatted as JSON. The method returns a JavaScript object or value that the JSON string represents.
- JSON.parse: The method to convert JSON text to JavaScript object.
- jsonString: A string containing valid JSON data.
javascript
const obj = JSON.parse('{"name":"Alice","age":25}');
Example
This example shows how to parse a JSON string into a JavaScript object and access its properties.
javascript
const jsonString = '{"name":"Alice","age":25,"isStudent":false}'; const user = JSON.parse(jsonString); console.log(user.name); // Alice console.log(user.age); // 25 console.log(user.isStudent); // false
Output
Alice
25
false
Common Pitfalls
Common mistakes when parsing JSON include:
- Passing an invalid JSON string causes a
SyntaxError. - Trying to parse a JavaScript object instead of a string.
- Using single quotes for JSON keys or strings, which is invalid in JSON.
Always ensure the JSON string is properly formatted and double-quoted.
javascript
try { // Wrong: JSON keys and strings must use double quotes const badJson = '{name:"Bob", age:30}'; JSON.parse(badJson); } catch (e) { console.log('Error:', e.message); } // Correct way const goodJson = '{"name":"Bob", "age":30}'; const obj = JSON.parse(goodJson); console.log(obj.name); // Bob
Output
Error: Unexpected token n in JSON at position 1
Bob
Quick Reference
- JSON.parse(string): Converts JSON string to JavaScript object.
- Input must be a valid JSON string with double quotes.
- Throws
SyntaxErrorif JSON is invalid. - Use
try...catchto handle errors safely.
Key Takeaways
Use JSON.parse() to convert JSON strings into JavaScript objects.
Ensure JSON strings use double quotes and valid syntax to avoid errors.
Wrap JSON.parse() in try-catch to handle invalid JSON safely.
Parsed objects can be accessed like normal JavaScript objects.
JSON.parse() only works on strings, not on JavaScript objects.