Javascript object serialization function - javascript

I need a function that can serialize object of type {"a":"val", "b":{}, "c":[{}]} without JSON.stringify (cause the environment simply does not has JSON object) or using jquery and any other library. The code bellow is what I have at this moment:
function objToString(obj) {
if (obj == null) return null;
var index = 0;
var str = '{';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += index != 0 ? "," : "";
str += '"' + p + '":' + (typeof (obj[p]) == 'object' ? objToString(obj[p]) : itemToJsonItem(obj[p]));
index++;
}
}
str += "}";
return str;
}
function itemToJsonItem(item) {
return isNaN(item) ? '"' + item + '"' : item;
}
This function can deal with objects, nested objects but not with arrays. Node "c" from mentioned object will looks like "c":{"0":{...}} and not like array. Unsurprising "c".constructor === Array is false cause it interpreted as function and not as array. This is complete code where you can see what happens.
<div id="div_result"></div>
<script>
var test = { "a": "val", "b": [{"c":"val c"}]};
function objToString(obj) {
if (obj == null) return null;
var index = 0;
var str = '{';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += index != 0 ? "," : "";
str += '"' + p + '":' + (typeof (obj[p]) == 'object' ? objToString(obj[p]) : itemToJsonItem(obj[p]));
index++;
}
}
str += "}";
return str;
}
function itemToJsonItem(item) {
return isNaN(item) ? '"' + item + '"' : item;
}
document.getElementById("div_result").innerHTML = objToString(test);
</script>
I will really appreciate help, at this moment serialized object created by toSerialize function inside of each object but we want to make it with outside standard function.

Try to use JSON 3. It is polyfill library for window.JSON. It exposes JSON.stringify and JSON.parse methods.

Related

Same function works in one js file while in other does not

I'm a begginer in javascript and I have one problem. The problem is that one function works in one javascript file and in the other no. In one of them I have a function which converts json to xml. This function works in that js archive. The problem comes in the other javascript file. I have to use that function on it, but that javascript files only has methods, so I've created a method with same code as the function, but it does not work there. It doesn't convert while in the other js yes. To use both method and function I've tried this.
var dat = JSON.stringify([{ "type": this.type, "sigma": this.sigma, "states": states }]);
return this.OBJtoXML2(dat);
How can I fix it?
1.js
function OBJtoXML(obj)
{
var xml = '';
for (var prop in obj)
{
xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
if (obj[prop] instanceof Array)
{
for (var array in obj[prop])
{
xml += "<" + prop + ">";
xml += OBJtoXML(new Object(obj[prop][array]));
xml += "</" + prop + ">";
}
}
else if (typeof obj[prop] == "object")
{
xml += OBJtoXML(new Object(obj[prop]));
}
else
{
xml += obj[prop];
}
xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
}
var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
return xml;
}
2.js
export default class StateChart {
constructor(type = 'AFD', sigma = 'ab', stateNaming = 'q') {
this.type = type;
this.sigma = sigma;
this.sigmaExtended = (this.type === 'AFD' ? this.sigma : '\u03F5' + this.sigma);
this.defaultName = stateNaming;
}
OBJtoXML2(obj) {
var xml = '';
for (var prop in obj)
{
xml += obj[prop] instanceof Array ? '' : "<" + prop + ">";
if (obj[prop] instanceof Array)
{
for (var array in obj[prop])
{
xml += "<" + prop + ">";
xml += OBJtoXML2(new Object(obj[prop][array]));
xml += "</" + prop + ">";
}
}
else if (typeof obj[prop] == "object")
{
xml += OBJtoXML2(new Object(obj[prop]));
}
else
{
xml += obj[prop];
}
xml += obj[prop] instanceof Array ? '' : "</" + prop + ">";
}
var xml = xml.replace(/<\/?[0-9]{1,}>/g, '');
return xml;
}
}

making gs file as both an apps script file as client js file

I have a custom file which can serve for both server side a.gs as well as cleint side a.js, both has same functions defined
instead of having a.gs and a.js how will I make
function include(filename) {
return HtmlService.createHtmlOutputFromFile('<script>'+a.gs+'</script>').getContent();
}
something like above.
In your doGet function you can check if a specific parameter is present and then send all or part of the code contained in a.gs to the client.
function doGet(e) {
if(e.parameter.func) {
var out = ContentService.createTextOutput(this[e.parameter.func].toString());
out.setMimeType(ContentService.MimeType.JAVASCRIPT);
return out;
}
}
Now you can add this line to your html file
<script type="text/javascript" src="https://script.google.com/macros/s/<id>/exec?func=myFunction"></script>
in order to use myFunction on the client.
But if you want to make everything in a.gs available to the client and not just a single function you could do this
function genCode2(obj) {
if(obj instanceof Array) return JSON.stringify(obj);
if(obj === null) return "null";
if(typeof(obj) === "undefined") return "undefined";
if(typeof(obj) === "object") {
var str = "{\n";
for(key in obj) {
if(typeof obj[key] === "function") {
var s = obj[key].toString() + "\n";
if(s.indexOf("[native code") < 0) str += "\"" + key + "\": " + s + ",\n";
} else {
str += "\"" + key + "\": " + genCode2(obj[key]) + ",\n";
}
}
return str + "\n}";
}
return JSON.stringify(obj);
}
function genCode(obj) {
var str = "";
for(key in obj) {
if(typeof obj[key] === "function") {
var s = obj[key].toString() + "\n";
if(s.indexOf("[native code") < 0) str += s;
} else {
str += "var " + key + " = " + genCode2(obj[key]) + ";\n";
}
}
return str + "";
}
function doGet(e) {
if(e.parameter.file === "a.gs") {
var out = ContentService.createTextOutput(genCode(this));
out.setMimeType(ContentService.MimeType.JAVASCRIPT);
return out;
}
}
And then put <script type="text/javascript" src="https://script.google.com/macros/s/<id>/exec?file=a.gs"></script> in the html file.
But on the other hand, maybe you could just put a js file into your google drive which you could then load in a.gs and send to the client or evaluate with eval.

How to serialize an object using javascript only (no Jquery)?

I have an object say image
look : {
name : "hello baby",
tag_list : "hello",
collection_id : 1,
category_id : 1
},
I want to serialize this object so that it can be sent via POST / GET request to the server. I cannot use JQUery for this purpose.
look[name]=hello
Try this:
var a = [];
for (var p in obj)
a.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
var qstring = a.join("&");
Code taken from http://www.codeproject.com/Tips/46827/Serialize-Object-in-Javascript
function serialize(obj)
{
var returnVal;
if(obj != undefined){
switch(obj.constructor)
{
case Array:
var vArr="[";
for(var i=0;i<obj.length;i++)
{
if(i>0) vArr += ",";
vArr += serialize(obj[i]);
}
vArr += "]"
return vArr;
case String:
returnVal = escape("'" + obj + "'");
return returnVal;
case Number:
returnVal = isFinite(obj) ? obj.toString() : null;
return returnVal;
case Date:
returnVal = "#" + obj + "#";
return returnVal;
default:
if(typeof obj == "object"){
var vobj=[];
for(attr in obj)
{
if(typeof obj[attr] != "function")
{
vobj.push('"' + attr + '":' + serialize(obj[attr]));
}
}
if(vobj.length >0)
return "{" + vobj.join(",") + "}";
else
return "{}";
}
else
{
return obj.toString();
}
}
}
return null;
}
For plain one dimensional objects, you can use
var ser ="";
for (var o in look) ser += "&"+o+"="+encodeURIComponent(look[o]);
alert(ser.substring(1));
This, adds a stringify method to your objects, and a parseJSON method to your strings.
source: JSON.org
Try using for..in loop. It gets each variable from object.
function serialize(obj)
{
var serialized = "";
for (variable in obj)
{
if(serialized != "") serialized += "&";
serialized += variable + "=" + encodeURIComponent(obj[variable]);
}
}
Simply use:
var look = {
name : "hello baby",
tag_list : "hello",
collection_id : 1,
category_id : 1
};
var serialized_object = JSON.stringify(look); // to serialize an object
var deserialized_object = eval('('+ serialized_object + ')'); // to deserialize an object

JSON to string variable dump

Is there a quick function to convert JSON objects received via jQuery getJSON to a string variable dump (for tracing/debugging purposes)?
Yes, JSON.stringify, can be found here, it's included in Firefox 3.5.4 and above.
A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html
var myJSONText = JSON.stringify(myObject, replacer);
You can use console.log() in Firebug or Chrome to get a good object view here, like this:
$.getJSON('my.json', function(data) {
console.log(data);
});
If you just want to view the string, look at the Resource view in Chrome or the Net view in Firebug to see the actual string response from the server (no need to convert it...you received it this way).
If you want to take that string and break it down for easy viewing, there's an excellent tool here: http://json.parser.online.fr/
i personally use the jquery dump plugin alot to dump objects, its a bit similar to php's print_r() function
Basic usage:
var obj = {
hubba: "Some string...",
bubba: 12.5,
dubba: ["One", "Two", "Three"]
}
$("#dump").append($.dump(obj));
/* will return:
Object {
hubba: "Some string..."
bubba: 12.5
dubba: Array (
0 => "One"
1 => "Two"
2 => "Three"
)
}
*/
Its very human readable, i also recommend this site http://json.parser.online.fr/ for creating/parsing/reading json, because it has nice colors
Here is the code I use. You should be able to adapt it to your needs.
function process_test_json() {
var jsonDataArr = { "Errors":[],"Success":true,"Data":{"step0":{"collectionNameStr":"dei_ideas_org_Private","url_root":"http:\/\/192.168.1.128:8500\/dei-ideas_org\/","collectionPathStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwrootchapter0-2\\verity_collections\\","writeVerityLastFileNameStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot\\chapter0-2\\VerityLastFileName.txt","doneFlag":false,"state_dbrec":{},"errorMsgStr":"","fileroot":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot"}}};
var htmlStr= "<h3 class='recurse_title'>[jsonDataArr] struct is</h3> " + recurse( jsonDataArr );
alert( htmlStr );
$( document.createElement('div') ).attr( "class", "main_div").html( htmlStr ).appendTo('div#out');
$("div#outAsHtml").text( $("div#out").html() );
}
function recurse( data ) {
var htmlRetStr = "<ul class='recurseObj' >";
for (var key in data) {
if (typeof(data[key])== 'object' && data[key] != null) {
htmlRetStr += "<li class='keyObj' ><strong>" + key + ":</strong><ul class='recurseSubObj' >";
htmlRetStr += recurse( data[key] );
htmlRetStr += '</ul ></li >';
} else {
htmlRetStr += ("<li class='keyStr' ><strong>" + key + ': </strong>"' + data[key] + '"</li >' );
}
};
htmlRetStr += '</ul >';
return( htmlRetStr );
}
</script>
</head><body>
<button onclick="process_test_json()" >Run process_test_json()</button>
<div id="out"></div>
<div id="outAsHtml"></div>
</body>
something along this?
function dump(x, indent) {
var indent = indent || '';
var s = '';
if (Array.isArray(x)) {
s += '[';
for (var i=0; i<x.length; i++) {
s += dump(x[i], indent)
if (i < x.length-1) s += ', ';
}
s +=']';
} else if (x === null) {
s = 'NULL';
} else switch(typeof x) {
case 'undefined':
s += 'UNDEFINED';
break;
case 'object':
s += "{ ";
var first = true;
for (var p in x) {
if (!first) s += indent + ' ';
s += p + ': ';
s += dump(x[p], indent + ' ');
s += "\n"
first = false;
}
s += '}';
break;
case 'boolean':
s += (x) ? 'TRUE' : 'FALSE';
break;
case 'number':
s += x;
break;
case 'string':
s += '"' + x + '"';
break;
case 'function':
s += '<FUNCTION>';
break;
default:
s += x;
break;
}
return s;
}

Convert a multidimensional javascript array to JSON?

What is the best way of converting a multi-dimensional javascript array to JSON?
Most of the popular JavaScript frameworks have JSON utility functions included. For instance, jQuery has a function that directly calls a url and loads the JSON result as an object : http://docs.jquery.com/Getjson
However, you can get an open-source JSON parser and stringifier from the json website :
https://github.com/douglascrockford/JSON-js
Then, simply include the code and use the JSON.stringify() method on your array.
The "best" way has been provided by the other posters. If you don't need the full encoding features of the referenced libraries, and only need to encode simple arrays, then try this:
<!DOCTYPE html>
<html>
<head>
<title>Simple functions for encoding Javascript arrays into JSON</title>
<script type="text/javascript">
window.onload = function() {
var a = [
[0, 1, '2', 3],
['0', '1', 2],
[],
['mf', 'cb']
],
b = [
0, '1', '2', 3, 'woohoo!'
];
alert(array2dToJson(a, 'a', '\n'));
alert(array1dToJson(b, 'b'));
};
function array2dToJson(a, p, nl) {
var i, j, s = '{"' + p + '":[';
nl = nl || '';
for (i = 0; i < a.length; ++i) {
s += nl + array1dToJson(a[i]);
if (i < a.length - 1) {
s += ',';
}
}
s += nl + ']}';
return s;
}
function array1dToJson(a, p) {
var i, s = '[';
for (i = 0; i < a.length; ++i) {
if (typeof a[i] == 'string') {
s += '"' + a[i] + '"';
}
else { // assume number type
s += a[i];
}
if (i < a.length - 1) {
s += ',';
}
}
s += ']';
if (p) {
return '{"' + p + '":' + s + '}';
}
return s;
}
</script>
</head>
<body>
</body>
</html>
Not sure I fully understand your question, but if you are trying to convert the object into a string of JSON then you probably want to look at the native JSON support in all the new browsers. Here's Resig's post on it. For browsers that don't yet support it try the json2.js library. JSON.stringify(obj) will convert your object to a string of JSON.
This will convert all combinations of arrays within objects and vice versa including function names:
function isArray(a){var g=a.constructor.toString();
if(g.match(/function Array()/)){return true;}else{return false;}
}
function objtostring(o){var a,k,f,freg=[],txt; if(typeof o!='object'){return false;}
if(isArray(o)){a={'t1':'[','t2':']','isarray':true}
}else {a={'t1':'{','t2':'}','isarray':false}}; txt=a.t1;
for(k in o){
if(!a.isarray)txt+="'"+k+"':";
if(typeof o[k]=='string'){txt+="'"+o[k]+"',";
}else if(typeof o[k]=='number'||typeof o[k]=='boolean'){txt+=o[k]+",";
}else if(typeof o[k]=='function'){f=o[k].toString();freg=f.match(/^function\s+(\w+)\s*\(/);
if(freg){txt+=freg[1]+",";}else{txt+=f+",";};
}else if(typeof o[k]=='object'){txt+=objtostring(o[k])+",";
}
}return txt.substr(0,txt.length-1)+a.t2;
}
You could use the encode function of this library.
I've modified a bit the code previously provided... because a JSON has this format: [{"object":{"property_1":"value_1","property_2":"value_2"}}]
So, the code would be...
<!DOCTYPE html>
<html>
<head>
<title>Simple functions for encoding Javascript arrays into JSON</title>
<script type="text/javascript">
window.onload = function(){
var a = [['property_1','value_1'],['property_2', 'value_2']];
alert("Comienzo..., paso ////"+a+"\\\\\\ a formato JSON");
var jsonSerialized = array2dToJson(a, 'object');
alert(jsonSerialized);
};
// Estructura de JSON [{"object":{"property_1":"value_1","property_2":"value_2"}}]
function array2dToJson(a, p, nl) {
var i, j, s = '[{"' + p + '":{';
nl = nl || '';
for (i = 0; i < a.length; ++i) {
s += nl + array1dToJson(a[i]);
if (i < a.length - 1) {
s += ',';
}
}
s += nl + '}}]';
return s;
}
function array1dToJson(a, p) {
var i, s = '';
for (i = 0; i < a.length; ++i) {
if (typeof a[i] == 'string') {
s += '"' + a[i] + '"';
}
else { // assume number type
s += a[i];
}
if (i < a.length - 1) {
s += ':';
}
}
s += '';
if (p) {
return '{"' + p + '":' + s + '}';
}
return s;
}
</script>
</head>
<body>
<h1>Convertir un Array a JSON...</h1>
</body>
</html>
var t = {}
for(var i=0;i<3;i++) {
var _main = {};
var _dis = {}
var _check = {};
_main["title"] = 'test';
_main["category"] = 'testing';
_dis[0] = '';
_dis[1] = '';
_dis[2] = '';
_dis[3] = '';
_check[0] = 'checked';
_check[1] = 'checked';
_check[2] = 'checked';
_check[3] = 'checked';
_main['values'] = _check;
_main['disabled'] = _dis;
t[i] = _main;
}
alert(JSON.stringify(t));
Try this
use this code and very simple develop for more two array
function getJSON(arrayID,arrayText) {
var JSON = "[";
//should arrayID length equal arrayText lenght and both against null
if (arrayID != null && arrayText != null && arrayID.length == arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
and 3 array
function getJSON(arrayID, arrayText, arrayNumber) {
var JSON = "[";
if (arrayID != null && arrayText != null && arrayNumber!=null && Math.min(arrayNumber.length,arrayID.length)==arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "',";
JSON += "number:'" + arrayNumber[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
JavaScript will correctly encode an object:
var a = new Object;
var a = {};
JavaScript will not encode an array:
var a = new Array();
var a = [];

Categories