JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string, eg:
var my_object = { key_1: "some text", key_2: true, key_3: 5 };
var object_as_string = JSON.stringify(my_object);
// "{"key_1":"some text","key_2":true,"key_3":5}"
typeof(object_as_string);
// "string"
JSON.parse turns a string of JSON text into a JavaScript object, eg:
var object_as_string_as_object = JSON.parse(object_as_string);
// {key_1: "some text", key_2: true, key_3: 5}
typeof(object_as_string_as_object);
// "object"
Answer from Quentin on Stack OverflowMicrosoft Foundry HTTP 500 error
[Performance] Deep Copy vs JSON Stringify / JSON Parse
Trying to learn fetch(), JSON.stringify() confusion
Json stringify
Videos
I am in the process of learning about client and server side and sending things back and forth.
I am running an express server and trying to get a log in my console on the server side.
This is my server.js:
//Imports
const express = require('express');
//Setup and configure app
const app = express();
const port = 5000;
//parse JSON files
app.use(express.json());
//serve static files
app.use(express.static('public'));
//Initialize app
app.listen(port, () => console.log(`Server listening on port ${port}!`));
app.post('/api', (request, response) => {
console.log(request.body);
});Why does this work and give an output on the console:
const data = {
name: 'john',
age: 28
};
const options = {
method: 'post',
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
};
fetch('/api', options);And when I change the variable data to a simple string it does not work:
const data = "hello";
And I will get this parsing error:
SyntaxError: Unexpected token " in JSON at position 0
Same behavior for integers.
Any help is greatly appreciated!
JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string, eg:
var my_object = { key_1: "some text", key_2: true, key_3: 5 };
var object_as_string = JSON.stringify(my_object);
// "{"key_1":"some text","key_2":true,"key_3":5}"
typeof(object_as_string);
// "string"
JSON.parse turns a string of JSON text into a JavaScript object, eg:
var object_as_string_as_object = JSON.parse(object_as_string);
// {key_1: "some text", key_2: true, key_3: 5}
typeof(object_as_string_as_object);
// "object"
JSON.parse() is for "parsing" something that was received as JSON.
JSON.stringify() is to create a JSON string out of an object/array.