json notation in function calls
I’ve been using JSON to help move objects, arrays, etc. between the client and server.
Basically, JSON is a serialisation method, which allows an object to be compressed to a string description, sent, and decompressed on the far side.
For example, the following is a “Kae” object:
{ name: "Kae", surname: "Verens", dependants: [ "Bronwyn Verens", "Jareth Verens" ], age: 29 }
The above is easy to understand, and can be compressed by stripping the spaces:
{name:"Kae",surname:"Verens",dependants:["Bronwyn Verens","Jareth Verens"],age:29}
There are four types of variable in the above; numeric, string, array, and object.
When you call a function in JavaScript with the above, after receiving it from the server, you must first “eval” it into a usable state.
Assuming the received serialised string is called “ret”, the following should be all that’s needed, assuming the values are going to the function “call_me()”.
call_me(eval(ret));
The above will work for each of the following strings:
ret="name=\"Kae\""; ret="[\"Bronwyn Verens\",\"Jareth Verens\"]"; ret="age=29";
But, this will not:
ret="{name:\"Kae\",surname:\"Verens\",dependants:[\"Bronwyn Verens\",\"Jareth Verens\"],age:29}";
The problem is that object notation ({ ... : ... }
) fails. It took me a while to figure out why.
This is valid code:
var kae={name:"Kae",surname:"Verens",dependants:["Bronwyn Verens","Jareth Verens"],age:29}; call_me(kae);
But, the following is not:
call_me({name:"Kae",surname:"Verens",dependants:["Bronwyn Verens","Jareth Verens"],age:29});
Why? Who knows… Anyway – this works:
call_me(({name:"Kae",surname:"Verens",dependants:["Bronwyn Verens","Jareth Verens"],age:29}));
Remember, the original premise was that the JSON was to be eval’ed while the function call was being created, so this ends up as:
call_me(eval(ret.charAt(0)=='{'?'('+ret+')':ret));
Ugly, but it works.