Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why when sending data over AJAX, do you have to JSON.stringify() your objects?

JSON stands for javascript object notation (as I'm sure you're aware), so why, when sending json via ajax do you need to turn it into a string to send it? Is it simply a formatting thing, or what?

This may belong in another place, if so, let me know, I'll close it and move it.

Obviously, I'm not looking for opinions, I'd like to know the actual answer.

Just to make sure I'm clear, I understand what JSON.stringify() does, and its counterpart JSON.parse(). I just want to know, why using stringify is required.

Thanks!

like image 699
Jacques ジャック Avatar asked Sep 14 '15 17:09

Jacques ジャック


People also ask

Why do we need to Stringify JSON?

The JSON. stringify() method in Javascript is used to create a JSON string out of it. While developing an application using JavaScript, many times it is needed to serialize the data to strings for storing the data into a database or for sending the data to an API or web server.

Does JSON Stringify work on objects?

JSON. stringify() will encode values that JSON supports. Objects with values that can be objects, arrays, strings, numbers and booleans. Anything else will be ignored or throw errors.

What is Stringify Ajax?

stringify() method converts JavaScript objects into strings.

What happens when you JSON Stringify an array?

The JSON Stringify array command converts the 4D array array into a serialized JSON array. This command performs the opposite action of the JSON PARSE ARRAY command. In array, pass a 4D array containing the data to be serialized.


2 Answers

when sending json via ajax do you need to turn it into a string to send it?

If it isn't a string, then it isn't JSON in the first place.

JSON is a text based data format. HTTP is a text based communications protocol.

JSON stands for javascript object notation

JSON is based on the syntax for JavaScript literals. A JavaScript object is not JSON.

like image 125
Quentin Avatar answered Oct 29 '22 07:10

Quentin


AJAX is all about HTTP requests, which are basically "text" requests to a server. That's the main reason why you have to stringify your object: That way it's turned into text that can "travel" over HTTP.

like image 38
alcfeoh Avatar answered Oct 29 '22 07:10

alcfeoh