Thursday, May 17, 2012

Obray Curry: A dish using Obect and Array

Most of us know to write a simple javascript object in object literal notation (JSON) as:

var o = { "p1" : "value1" , "p2" : "value2" };

We also know that, we can add property dynamically as following ways:

  • o.p3 = "value3";
  • o["p4"] = "value4";

Most of us also know that we can write a simple javascript array object notation (JSON) as :

var arr = [10,20,30];

So far so good. Today I have a question to share.

How about making a curry of array and object.

Ain't that f**king lovely!!!!

var a = [10, 20, 30, 40 ];
a.p1 = "kiazen";
a["p2"] = "krook";

lets execute this code and see the object.
Here is the output::

1. What do we call this "a" as object or array ?
     I'll be referring to Obray (object array).

2. How do we represent this Obray.
     My assumed representation:  
{ [ 10, 20, 30 ], "p1": "kiazen", "p2": "krook" }

The site jsonlint failed to process my assumed representation

which is absolutely correct as per ECMA-262. scroll below to know exact reason.

Again on the server side, C# allows us to emulate similar structure implementation:

class MyArray[T]
        List[T] _list = new List[T]();
        public string p1 { get; set; }
        public string p2 { get; set; }
        public T this[int i]
            get { return _list[i]; }
            set {
                if (_list.Count < i)
                    _list[i] = value;

MyArray[int] obj = new MyArray[int]();
  obj.p1 = "kiazen";
  obj.p2 = "krook";
  obj[0] = 10;
  obj[1] = 20;
  obj[2] = 30;

So far so good, but if we serialize it, what should be the JSON ?
*used Newtonsoft.Json.dll for object to json conversion.
It gave me the following output:


What happened to the array while serialization?
Well thanks to ECMA-262.pdf which tells us about the parsing.
Parsing (serializing/deserializing) is on either object or array. And while serializing, this component will be an object and not an array and hence, the object serialization is happening.

image source:

so there is no options for our Obray, Its either Object or Array !!!

I have raised the same discussion point in development forum []. You are free to put your opinion here.

I think we need some improvisation in json as well ?

No comments:

Post a Comment