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

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

Related

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 do I convert the object passed in to an array of strings

function objectToArray (object) {
var array = [];
var str = "";
for (var key in object) {
array.push(key);
array.push(object[key]);
if (object.hasOwnProperty(key)) {
str += key + " is " + object[key] + "";
}
}
console.log(array);
}
objectToArray({name: "Marcia", age: 101});
The output is [ 'name', 'Marcia', 'age', 101 ] and I need it to be ["name is Marcia", "age is 101"].
Instead of this:
array.push(key);
array.push(object[key]);
if (object.hasOwnProperty(key)) {
str += key + " is " + object[key] + "";
}
You want this:
if (object.hasOwnProperty(key)) {
array.push( key + " is " + object[key] + "" );
}
#VoteyDisciple has correctly pointed out where you went wrong with your approach. An alternate (shorter) way to implement your function is:
function objectToArray (object) {
return Object.keys(object).map(function (key) {
return key + " is " + object[key];
});
}
var arr = objectToArray({name: "Marcia", age: 101});
console.log(arr);

Javascript object serialization function

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.

How can iterate over JSON object and print its properties and their values?

I want to navigate each property in the JSON below in JavaScript. The below JSON contains two records for reference but in real time will have numerous such records.
{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}
I want to get the values of the fields "Status", "CreatorLoginId" and "Name" to assign them to something else.
How should I do it?
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var pr in myJSON)
{
console.log(myJSON[pr][0].Status);
console.log(myJSON[pr][0].CreatorLoginId);
console.log(myJSON[pr][0].Name);
}
Print how? If you mean output to the js console it would be
for (index in object) {
console.log(index + ': ' + object[index]);
}
If you mean add it to a web page, just replace console.log with a little markup:
var parent = document.getElementById('parentID');
for (index in object) {
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
For nested objects (including arrays)
function print(object, parent) {
for (index in object) {
if (typeof object[index] == 'object') {
print(object[index});
}
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
}
EDIT: don't forget to JSON.parse(): the string first before iterating
//Iterating through the groups
for (var currentRecord in groupInformation)
{
store.data.items.push({serial: {}, groupName: {}, createdBy: {}, status: {} });
store.data.items[iNoOfGroups].serial = iNoOfGroups + 1;
store.data.items[iNoOfGroups].groupName = groupInformation[currentRecord][0].Name;
store.data.items[iNoOfGroups].createdBy = groupInformation[currentRecord][0].CreatorLoginId;
store.data.items[iNoOfGroups].status = groupInformation[currentRecord][0].Status;
iNoOfGroups++;
}
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var key in myJSON){
console.log(myJSON[key][0].Status);
console.log(myJSON[key][0].CreatorLoginId);
console.log(myJSON[key][0].Name);
}`

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