javascript serialization - a short library - javascript

I have to save in a cookie a small amount of data.
Would be wonderful if javascript (natively) provide a way to serialize/deserialize an array (or an object).
To be honest, I have tried to write my own piece of code, it is based on the idea that we could serialize an array recursively converting it in a key/value querystring and viceversa.
Well, this is the code:
var lib = {
serialize : function(_a) {
var s = '', enc = encodeURIComponent;
for (var k in _a) {
if (s) s += '&';
s += enc(k) + '=' + ((typeof _a[k] == 'object') ? '?'+enc(lib.serialize(_a[k])) : enc(_a[k]));
}
return s;
},
deserialize : function(_s) {
var a = [], dec = decodeURIComponent;
var list = _s.split('&');
for (var c in list) {
var kv = list[c].split('=');
var v = kv[1].split('?');
kv[1] = (v.length > 1) ? lib.deserialize(dec(v[1])) : dec(kv[1]);
a[dec(kv[0])] = kv[1];
}
return a;
}
};
http://jsfiddle.net/P7wT8/
Although it seems to works quite fine, could someone suggest me something of better and shorter?
A piece of code or a library, something of little and easy to implement Javascript array serialize/deserialize ?

I think your best approach is to use JSON.
JSON.stringify and JSON.parse can encode and decode the values.
JSON is a standard format nowadays, so it is clearer to other developers what's happening.
The only limitation is that IE 7 and below do not support JSON functions natively and require a library.

Related

filter a json object and loop results grep

I have the following code but I know that there must be a more efficient way to get to my end results. I need a comma separated string but when I try to use .toString I know that I'm not using it in the right place. I've included the code that I am currently using
function load_data() {
var response = [
{"email": "a#123.com","pmid": ["a22222", "a444444", "a555555", "a7777777", "a8888888"]},
{"email": "b#123.com", "pmid": ["b22222", "b444444", "b555555", "b7777777", "b8888888"]},
{"email": "c#123.com", "pmid": ["c22222", "c444444", "c555555", "c7777777", "c8888888"]},
{"email": "d#123.com", "pmid": ["d22222", "d444444", "d555555", "d7777777", "d8888888"]}
];
var singleEmail = $.grep(response, function (element, index) {
return element.email == 'a#123.com';
});
var obj = singleEmail[0];
var pmid = obj.pmid;
var pmidList = ''
for (var i = 0; i < pmid.length; i++) {
pmidList += pmid[i] + ',';
}
alert(pmidList);
}
Also is using grep any more efficient than just looping?
Thanks
Using jQuery is never more efficient. JS has many useful methods these days. Check MDN for browser support though.
Find the right element:
// modern
const element = response.find((el) => el.email == 'a#123.com');
// compatible
var element = response.find(function(el) {
return el.email == 'a#123.com';
});
Stringify the array:
const pmidList = element.pmid.join(',');
// or var for compatibility
pmidList won't have a trailing , like your code, but I'm guessing that's good.
References & support:
const vs var
arrow functions
array.find vs array.filter (grep)

How to assign $_GET value to a variable using pure JavaScript

Hi guys can How to assign $_GET value to a variable using pure JavaScript I have HTML structure not php
You could do something like this
function getGETParameter(key) {
var params = window.location.search.slice(1).split('&'),
i = params.length;
key += '=';
while (i-- > 0) {
if (params[i].lastIndexOf(key, 0) === 0)
return params[i].slice(key.length);
}
return false;
}
You may also want to consider if you want to use decodeURIComponent on these values as they may be URI encoded
If you want to also permit keys to be URI encoded then this method starts to have issues and you would have to create an Object mapping, which would look something like this
function getGETParameter(key) {
var params = window.location.search.slice(1).split('&'),
i = params.length,
j,
o = Object.create(null);
for (i = 0; i < params.length; ++i) {
j = params[i].indexOf('=');
if (j === -1) // how do you want to treat found but no value?
o[decodeURIComponent(params[i])] = null;
else
o[decodeURIComponent(params[i].slice(0, j))] = decodeURIComponent(params[i].slice(j + 1));
}
if (key in o) return o[key];
return false; // how do you wan to treat not found?
}
You could also create and cache this Object in advance instead of generating it for each invocation
combine the php code and javascript code !
var x=<?php echo $_GET['whatever'];?>;
so first the php code is being executed server-side and then it's result in html is assigned to a variable in javascript ...

Transform JSON Object into numerical String and vice versa

(Apologies if a similar question has been asked, I could not find it)
Basically I have a JSON object with around 10 properties (fixed amount) that contains personal settings for an app without a user system and I would like users to be able to obtain a code that converts to that object with the proper values for each property. That way, they would be able to access the app with their settings using a permalink.
Question is: Is there a method or a specific indicated technique to transform JSON serialized objects (i.e. JSON string) into numbers, or an hexadecimal code? I've seen several websites do a similar thing from a user point of view.
My approach since I have a finite set of properties and possible values would be to hardcode the string (e.g. if property 1 has value x, first char in string is 1, if it has value y, then it's 2, etc...) but I'm wondering if there is anything best suited for that kind of thing.
Lets do this.
setup is object I used for testing
var setup = { "abc" : "asdasd",
"special" : "my wife hates me",
"Kids" : 7564
};
function to generate link:
function generateLinkWithSpecialSetup(setup) {
var str = JSON.stringify(setup);
var hash = "";
for(var i =0; i<str.length;i++) {
hash += str.charCodeAt(i).toString(16);
}
return "example.com/special-setup/#" + hash;
}
functions to find setup from hash:
function findSetupFromHash() {
var hash = window.location.hash.substring(1);
var str = hex2a(hash);
return JSON.parse(str);
}
function hex2a(hexx) {
var hex = hexx.toString(); //force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}

encrypting an object in javascript

var Obj = {};
Obj.ID = e.row.ID;
Obj.firstName = e.row.firstName;
Obj.lastName = e.row.lastName;
This is my object, and i save this object in a file. now before saving into file, i want to encrypt it and save and while reading i want to decrypt and read.
var newFile = FileSystemPath;
newFile.write(JSON.stringify(object));
Should i encrypt the object before stringifying it or after it.
What are the ways to encrypt an object in javascript. Any examples
would be great.
You can't really encrypt objects, but you can encrypt strings, so you should probably first do a object serialization (JSON.stringify) and then encrypt it with a symmetric encryption algorithm so you would be able to decode the object later.
I can't really provide a good example, because javascript will always have serious security problems (being a client-side programming language), and even if you try a rather complex algorithm (such as AES) it will still be vulnerable, because the user can just see your source code, thus see your encription/decription algorithms.
If you just want to alter the string a bit so it can't be deciphered on the first look, you can simply use some built-in javascript methods (such as encodeURI/decodeURI) or you can do some character replacements or even use salts.
Here's a sample demo of how you can "encrypt" an object :
function encrypt(o, salt) {
o = JSON.stringify(o).split('');
for(var i = 0, l = o.length; i < l; i++)
if(o[i] == '{')
o[i] = '}';
else if(o[i] == '}')
o[i] = '{';
return encodeURI(salt + o.join(''));
}
function decrypt(o, salt) {
o = decodeURI(o);
if(salt && o.indexOf(salt) != 0)
throw new Error('object cannot be decrypted');
o = o.substring(salt.length).split('');
for(var i = 0, l = o.length; i < l; i++)
if(o[i] == '{')
o[i] = '}';
else if(o[i] == '}')
o[i] = '{';
return JSON.parse(o.join(''));
}
var obj = {
key : 'value',
3 : 1
};
var salt = "some string here";
var encrypted = encrypt(obj, salt);
var decrypted = decrypt(encripted, salt);
Of course, this is just an example and you should modify it in order to encrypt more complex objects, where you need to encrypt functions, or where the object has circular references.

Is the usage of eval() justified here?

The JavaScript object data has an attribute 'amplitudes' which is a string concatenated bunch of bitmask arrays coming from the server.
var data = {
"amplitudes":
"[1,1,1,4,1,1],[1,1,1,1,1,1],[1,1,4,1,9,1],[1,1,9,1,16,1],[1,32,1,1,1,9],[4,4,4,1,1,1]"
}
.
This needs be broken down into six independant arrays. I am using a combination of split() and eval() to accomplish it in the following way:
var amplitudes = [];
amplitudes = data.amplitudes.split("],[");
for(var i=0;i<amplitudes.length;i+=1){
(i+1)%2>0 ? amplitudes[i] = amplitudes[i] + "]" : amplitudes[i] = "[" + amplitudes[i];
amplitudes[i] = eval(amplitudes[i]);
}
Questions
1) Is there a more elegant and efficient way to do this?? I am not too happy with the usage of eval(), but had a feeling split is more efficient than a regex? I haven't run a benchmark yet.
2) I am also open to manipulating the format in which the field 'amplitudes' is stored in database so that my overall design gets simpler.
Suggestions welcome
As you probably process your data with a server-side language simply make it generate a JavaScript array. If you have an array in your server-side code, use a JSON encoder to build the JavaScript object/array.
var data = {
"amplitudes": [[1,1,1,4,1,1], [1,1,1,1,1,1], [1,1,4,1,9,1], [1,1,9,1,16,1], [1,32,1,1,1,9], [4,4,4,1,1,1]]
}
If you cannot change what you get from the server, you can do it using eval but in a much simpler way:
var str = "[1,1,1,4,1,1],[1,1,1,1,1,1],[1,1,4,1,9,1],[1,1,9,1,16,1],[1,32,1,1,1,9],[4,4,4,1,1,1]";
var arr = eval('[' + str + ']');
If you can change the server, just have the "amplitudes" property be an array of arrays, and don't write it out with quotes:
var data = {
amplitudes: [ [1, 1, 1, 4, 1, 1 ], [ 1, 1, 1, 1, 1, 1 ], ... ]
};
Now your client need do no decoding at all.
The eval() function is generally used to decode JSON data that is considered 'safe', as using eval on user-defined data can result in XSS attacks. Anyway, you can make your code more elegant by using regular expressions to match the arrays, then use eval to decode the array components:
var matches = data.amplitudes.match(/\[.*?\]/g);
var amplitudes = [];
if (matches != null && matches.length > 0) {
for (var i = 0; i < matches.length; i++) {
amplitudes[i] = eval(matches[i]);
}
}
Well you could try using JSON to pass a javascript object directly from the server, compared to just returning a string. Almost every server side language supports JSON encoding/decoding in some form.
http://www.json.org/

Categories