Native JSON Methods
JavaScript natively supports JSON with two core methods:
JSON.stringify()
Converts a JavaScript object to a JSON string
const obj = {name: "John Doe", age: 30};
const json = JSON.stringify(obj);
console.log(json);
// {"name":"John Doe","age":30}
JSON.parse()
Converts a JSON string to a JavaScript object
const json = '{"name":"Jane Smith","age":28}';
const obj = JSON.parse(json);
console.log(obj.name);
// Jane Smith
Debugging Tip
Is the output of JSON.stringify too long and hard to read? Although you
can format it with parameters, it's better to copy it to an online tool to view the
tree structure.
Client-Server Data Interaction
Using Fetch API
// Fetch Data
fetch('/api/users')
.then(response => response.json())
.then(data => {
console.log(data);
// Update Page
})
.catch(error => console.error('Error:', error));
// Send Data
fetch('/api/users', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({name: 'John Doe', age: 30})
})
.then(response => response.json())
.then(data => console.log(data));
LocalStorage
LocalStorage can only store strings, so you need JSON to store objects:
// Save Data
const user = {name: 'John Doe', age: 30};
localStorage.setItem('user', JSON.stringify(user));
// Read Data
const stored = localStorage.getItem('user');
const userObj = JSON.parse(stored);
console.log(userObj.name);