JSON.stringify() is a method in JavaScript that converts a JavaScript object or value into a JSON (JavaScript Object Notation) string.
stringify.js
const emp = { id : 1, name : "Krishna", address: { city: "Bangalore", state: "Karnataka" } } const empJson = JSON.stringify(emp); console.log(empJson);
Output
{"id":1,"name":"Krishna","address":{"city":"Bangalore","state":"Karnataka"}}
Why to use JSON.stringify() while posting data to an API?
When sending data from a web application to a server (for example, using the fetch API or XMLHttpRequest), the data must be serialized into a string format because HTTP requests are text-based. JSON is the most commonly used format for this purpose.
postData.js
async function createNewPost() { const response = await fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", body: JSON.stringify({ title: "foo", body: "bar", userId: 1, }), headers: { "Content-type": "application/json; charset=UTF-8", }, }); if (!response.ok) { console.error("Error Occured while posting the data"); return; } const body = await response.json(); console.log(body); } createNewPost();
Output
{ title: 'foo', body: 'bar', userId: 1, id: 101 }
No comments:
Post a Comment