Sending JSON Data in an API Request
When making an API request, the JSON data is typically sent as a string in the body of the HTTP request:
const data = {
name: "Alice",
age: 25
};
fetch('https://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data) // Convert the JSON object to a string
})
.then(response => response.json())
.then(data => console.log(data));
Parsing JSON Strings
When a JSON string is received (e.g., from a network request), it needs to be parsed into a JavaScript object to be manipulated by the code.
Example:
const jsonString = '{"name": "Alice", "age": 25}';
const data = JSON.parse(jsonString); // Converts JSON string to JavaScript object
console.log(data.name); // Outputs: Alice
Storing JSON data as a string
Storing JSON as a string in files or databases is convenient because it is compact, human-readable, and easy to serialize and deserialize.
Example:
const fs = require('fs');
const data = {
name: "Alice",
age: 25
};
fs.writeFile('data.json', JSON.stringify(data), (err) => {
if (err) throw err;
console.log('Data has been saved!');
});