JSON Encoder/Decoder For JavaScript
JSON(JavaScript Object Notation) is a lightweight computer data interchange format. It is a text-based, semi-readable format for representing simple data structures and associative arrays. The main advantage of using JSON is that it can be parsed into an object using very little code - and for this reason, many people(including me) prefer using it as the ajax response format.
JSON Decoder/Parser
As I said earlier, parsing JSON is very easy. All you have to do is...
var json_data_object = eval("(" + json_string + ")");
If you have moral objections with using eval, there are other JSON parsers that don't use eval. Use one of those.
JSON Encoder
Unlike decoding JSON, encoding JSON in JavaScript takes a bit of work. Usually you don't have to do that in the client side - generating JSON strings are the function of server side script. And server side language have functions for it. For example, PHP has json_encode.
But there are occasions when you want to encode a data structure into a string in JavaScript. A good example for this is saving data structures to a cookie. Cookies can only store strings. If you want to store a data structure in it, you have to use some encoding scheme. And since we are working in javascript, JSON is the obvious choice. I recently had to do this - so I wrote a function to encode a data structure into a JSON string. Yes, I know there are a lot of scripts that does this. But I like re-inventing the wheel - it is one of my favorite pass times.
Then again, I was not re-inventing a JSON encoder - I was just translating a JSON parser I wrote in PHP to javascript.
/**
* Converts the given data structure to a JSON string.
* Argument: arr - The data structure that must be converted to JSON
* Example: var json_string = array2json(['e', {pluribus: 'unum'}]);
* var json = array2json({"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}});
* http://www.openjs.com/scripts/data/json_encode.php
*/
function array2json(arr) {
var parts = [];
var is_list = (Object.prototype.toString.apply(arr) === '[object Array]');
for(var key in arr) {
var value = arr[key];
if(typeof value == "object") { //Custom handling for arrays
if(is_list) parts.push(array2json(value)); /* :RECURSION: */
else parts.push('"' + key + '":' + array2json(value)); /* :RECURSION: */
//else parts[key] = array2json(value); /* :RECURSION: */
} else {
var str = "";
if(!is_list) str = '"' + key + '":';
//Custom handling for multiple data types
if(typeof value == "number") str += value; //Numbers
else if(value === false) str += 'false'; //The booleans
else if(value === true) str += 'true';
else str += '"' + value + '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Functions?)
parts.push(str);
}
}
var json = parts.join(",");
if(is_list) return '[' + json + ']';//Return numerical JSON
return '{' + json + '}';//Return associative JSON
}
Usage Example
var json_string = array2json(['e', {pluribus: 'unum'}]);//Returns '["e", {"pluribus": "unum"}]'
var data = {
"success":"Sweet",
"failure":false,
"empty_array":[],
"numbers":[1,2,3],
"info":{
"name":"Binny",
"site":"http:\/\/www.openjs.com\/"
}
};
var json = array2json(data); // Returns {"success":"Sweet","failure":false,"empty_array":[],"numbers":[1,2,3],"info":{"name":"Binny","site":"http:\/\/www.openjs.com\/"}}
License
BSD License
blog comments powered by Disqus