Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it necessary to call JSON.stringify when submitting object data to server?

I am working through a new project using Knockout.js and the ASP.NET web ApiController. Many of the examples I see perform some manual JSON serialization before posting the data to the server. Additionally, the request content type is equally often set to "application/json".

I am wondering why this is necessary. I'm assuming there's something I haven't yet encountered that makes this either required or at least preferable.

Currently, I am having no issues sending any data I desire to the server using these jQuery ajax options:

        cache: false,
        traditional: true,
        type: 'POST',

Here's sample JS object and corresponding server-side C# model object that POSTs and binds to the ApiController action method just fine.

//JS object
var requestDataObject = {
    accountId: vm.accountId,
    range: [1, "a'b\"c", 3],
    start: new Date(2012, 12, 12)
};

//C# model object
public class RequestData
{
    public int AccountId { get; set; }
    public string[] Range { get; set; }
    public DateTime Start { get; set; }
}

//Action method signature
[HttpPost]
public HttpResponseMessage GetAccountUsage(RequestData requestData){
    ...

What am I missing?

like image 431
Joseph Gabriel Avatar asked Oct 19 '25 07:10

Joseph Gabriel


1 Answers

Historically, GET (and subsequently POST) can only send key-value pairs, and the keys should be unique.

When PHP came, it defined "if a key contains square brackets, let's build an array". This enabled the programmers to call their checkboxes name="chkbox[]", let the form submit normally, and read $_POST['chkbox'] as an array. Some other server languages defined, "if a key is repeated in the query string, let's build an array".

If the key names[]=1 was to be supported, why not names[a][b][c]=1? The servers knew what they should do: Assign names = {a:{b:{c:"1"}}}.

This enables the programmers to encode objects to query the string, with a few catches:

  • Every value is a string
  • There is no distinction between arrays and objects with numeric keys. PHP doesn't care, but some servers might.
  • There is no way to encode empty objects or arrays. With traditional forms, this results in empty arrays missing. PHP does care. JQuery solves that by sending an empty string instead.
  • It's extremely inefficient as the path has to be repeated for each value: checkboxes[]=ch1&checkboxes[]=ch2&... vs. checkboxes=["ch1","ch2",...]
  • you have to know the target platform as PHP doesn't like traditional (or resort to reading from postVars.get("names[]") on servers that do)
  • some servers don't understand this encoding at all.

With JSON,

  • you can encode numbers, strings, null, ...
  • ... arrays, objects...
  • empty arrays and objects are easy to represent. You don't have to test the presence of each array and object just because it might be empty.
  • no key is ever repeated, so you don't need to keep your keys short
  • there is no confusion how to represent an array with automatic keys; a JSON encodes the same structure no matter where it's sent.
  • Parsing JSON is possible in any language. Lot of languages have JSON support built in, the rest can fetch a library.
  • you only have to write one extra line on the server and the client.

In short, if you only need to encode key-value pairs, that's what a plain GET or POST excels at. If you need to encode arrays, JSON is definitely worth considering. If you need anything more complex, JSON is the only way to go with some servers.

like image 110
John Dvorak Avatar answered Oct 20 '25 22:10

John Dvorak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!