Why must we stringify arrays but not objects over requests? - javascript

Last night I was sending some data to my server via AJAX (specifically, $.post), when I ran into the issue that JavaScript Arrays needed to be "stringified" and applied as a field to an object before being sent. That is:
$.post("/myUrl/", {"myKey": json.stringify(myArray)}, ... );
If I didn't perform the stringify, the format of the POST would get screwed up by the time it reached Django.
Why do arrays need to be stringified for requests when objects can just be sent as is? Or, does this vary wildly on the back-end being used?

The object doesn't get sent "as is". jQuery recodes the object to URL key/values pairs, for example:
http://this.url?myKey=stringifiedArray.
The documentation has more information on this.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
Objects are used because they're an easy data structure for developers to manipulate.

Related

When exchanging data between a browser and a server, the data can only be text. Why?

I understood why we are using JSON to exchange data between browser and server in place of XML but I could not understand why we are using only string type of JSON even we have six different value datatype, I mean why we can't use integer or Boolean or any other value datatype.
Hope you guys understand what I'm trying to say, Thanks in advance.
If I understand correctly, the limitation is because of the way data needs to be encoded to be sent over HTTP and ultimately over the wire. You json object (or xml,etc) is ultimately just a payload for HTTP (which is just a payload for tcp in turn and so on).
HTTP inherently does not and should not identify data types in payload, it is just an array for HTTP. You can select how to represent this array i.e. how to encode it; It can be string (ascii, utf-8, etc) or binary but it has to be uniform for the whole payload.
HTTP does offer different encoding methods of payload which can be interpreted by the receiver by looking at the content-type header and accordingly decode the data.
Hope this helps.
why we are using only string type of JSON
Uhm, we're not. I believe you're misunderstanding something here. HTTP responses can really contain anything; every time you download a PDF or an image from a web server, the web server is sending a binary payload, which can literally be anything. So it's not even true that all HTTP bodies must be text.
To exchange data between systems, you send bytes. For these bytes to mean anything, you need an encoding scheme. Image formats have a particular way in which bytes need to be arranged, and when properly doing so, you can send pictures with them. Same for PDFs, video, audio, and anything else (including text).
If you want to send structured data, you need to express that structure somehow. How do you send a, for example, PHP array over HTTP…? (Substitute your equivalent list data structure in your language of choice.) You can't. A PHP array is a specific data structure in memory of a PHP runtime, sending that as is over HTTP has no meaning (because it deals with internal pointers and such). This array needs to be serialised first. There are many possible serialisation methods, some of them using binary data, and some using formats which are human readable to varying degrees. You could simply join all array elements with commas and .split(',') them again on the other end, but that's rather simplistic and misses many more complex cases and edge cases.
JSON and XML (and YAML and whatnot) are human readable formats which can serialise data structures like arrays (and dictionaries and numbers and booleans etc), and which happen to be text-based (purposely, to make them developer-friendly). You can use any of those data types JSON allows. Nothing prevents you from doing so, and not using them is insane. JSON and XML also happen to be two formats easily parsed with tools built into every browser. You could use any other binary format too, but then you'd have to manually parse it in Javascript.
Communication between browser and server can be done in many ways. It's just that JSON comes out of the box. You can use protobuf, xml and plethora of other data serialization techniques to communicate with the server as long as both sides understand what's the communication medium. On the browser side, you have to probably implement protobuf, xml etc serialization/deserialization on your own in javascript.
Any valid JSON is permitted for data exchange. The keys are string quoted but the values can be strings, numbers, booleans, array or other objects itself. Though before transmission, everything is converted into a string and the receiving side parses it into the correct format.

Sending a js model in json or url encoded format?

Some js frameworks (e.g. Backbone.js) send model data in json format by default. Is there any pros for that? At least in PHP post and get parameters are more easily accessible in comparison with json request body.
URL encoded data only defines a mechanism for encoding key=value string pairs. (PHP extends that to support nested data structures, but not in a backend technology agnostic way).
JSON supports arrays, objects, strings, numbers, booleans and null.

Framework for encode redundant field names in JSON objects and decode it in javascript?

I'm retrieving below json object array data from a web service. As you can see Id, ProjectId, Owner fields are repeated for all the objects(I know its JSON convention). But I'm thinking is there any library/framework to minimize that?
like when json is serializing serialize the field name to a unicode char and deserialize it in javascript again to readable field name.
[
{
"Id":0,
"ProjectId":"PJ4604",
"Owner":"SURENJ1",
},
{
"Id":1,
"ProjectId":"PJ4604",
"Owner":"SURENJ1",
},
{
"Id":2,
"ProjectId":"PJ4604",
"Owner":"SURENJ1"
}]
jQuery's extend does something similar to what you're asking for: http://api.jquery.com/jQuery.extend/
Essentially, it will just keep overwriting the first object with the value of the second, so any repeated fields will be overwritten and merged into a single object with only your unique fields.
The usual way to do this is to use HTTP compression. When enabled, the server and browser will compress and decompress the data transparently. You don't need anything specific to JSON.
The specifics on enabling it will depend on your HTTP server (and possibly any server side languages you use to generate the JSON).

extjs datastore send to server (datastore -> json)

Getting Json from the Server and displaying it in the grid is relatively straight forward. In the application (http://pssnet.com/~devone/extjs3/loadSelection5.html) I generate a dynamic grid datastore. I need to send this to the Server for further processing.
If there is a way to convert the data store to json, I can strigyfy it and send it a param...as in jQuery.
Otherthan looping through the whole datastore to build json, there seems no methods.
Thank you.
(I can guarantee that the following applies to Ext > 2.3)
Because Ext.data.Store stores an array of Ext.data.Record objects, it has no direct access to the underlying data (Ext.data.Record encapsulates the data), so, indeed, there's no direct way to do it. But Ext.data.Record itself has a public property called "data" (an object with the field:value properties), which you can collect into an array (e.g. using the Ext.data.Store#each method) and then encode with Ext.encode() to "stringify" it.

sending hierarchical data from javascript over flat POST request

I have a page on which user can dynamically create some identical groups of inputs, fill it and send to server.
<input type="text" name="firstName"/>
<input type="text" name="lastName"/>
What is a preferable way of sending this data to server?
Maybe there are some simple ways of emulating hierarhical data over POST request, avoiding XML structures?
Different "name" attribute values ("firstName1", "firstname2")?
Creating ID for each group or input?
Relying on the order of name-value pairs in the POST request?
EDIT: Of course i know about JSON. But just to use some minimal hierarchies I would like to follow the second answer: Rely on the order of firstname-lastname in post request.
You could use JSON serialization instead of XML. On the browser side you could use one of the Javascript JSON libraries like this one and there's plenty of implementations for server side languages, which you can use for deserialization.
If the data pairs are ordered, you don’t need additional identifiers as the order already identifies the data pairs. So you could just use firstName and lastName for every data pair:
firstName=First%20Name%201&lastName=Last%02Name%201&firstName=First%20Name%202&lastName=Last%20Name%202&…
You server-side application then just combines each data pair.
But some languages/systems already do this when the data has a special format. In PHP you could use the arg[] syntax to automatically get an array of the data.

Categories