Serialize JavaScript object into JSON string - javascript

I have this JavaScript prototype:
Utils.MyClass1 = function(id, member) {
this.id = id;
this.member = member;
}
and I create a new object:
var myobject = new MyClass1("5678999", "text");
If I do:
console.log(JSON.stringify(myobject));
the result is:
{"id":"5678999", "member":"text"}
but I need for the type of the objects to be included in the JSON string, like this:
"MyClass1": { "id":"5678999", "member":"text"}
Is there a fast way to do this using a framework or something? Or do I need to implement a toJson() method in the class and do it manually?

var myobject = new MyClass1("5678999", "text");
var dto = { MyClass1: myobject };
console.log(JSON.stringify(dto));
EDIT:
JSON.stringify will stringify all 'properties' of your class. If you want to persist only some of them, you can specify them individually like this:
var dto = { MyClass1: {
property1: myobject.property1,
property2: myobject.property2
}};

It's just JSON? You can stringify() JSON:
var obj = {
cons: [[String, 'some', 'somemore']],
func: function(param, param2){
param2.some = 'bla';
}
};
var text = JSON.stringify(obj);
And parse back to JSON again with parse():
var myVar = JSON.parse(text);
If you have functions in the object, use this to serialize:
function objToString(obj, ndeep) {
switch(typeof obj){
case "string": return '"'+obj+'"';
case "function": return obj.name || obj.toString();
case "object":
var indent = Array(ndeep||1).join('\t'), isArray = Array.isArray(obj);
return ('{['[+isArray] + Object.keys(obj).map(function(key){
return '\n\t' + indent +(isArray?'': key + ': ' )+ objToString(obj[key], (ndeep||1)+1);
}).join(',') + '\n' + indent + '}]'[+isArray]).replace(/[\s\t\n]+(?=(?:[^\'"]*[\'"][^\'"]*[\'"])*[^\'"]*$)/g,'');
default: return obj.toString();
}
}
Examples:
Serialize:
var text = objToString(obj); //To Serialize Object
Result:
"{cons:[[String,"some","somemore"]],func:function(param,param2){param2.some='bla';}}"
Deserialize:
Var myObj = eval('('+text+')');//To UnSerialize
Result:
Object {cons: Array[1], func: function, spoof: function}

Well, the type of an element is not standardly serialized, so you should add it manually. For example
var myobject = new MyClass1("5678999", "text");
var toJSONobject = { objectType: myobject.constructor, objectProperties: myobject };
console.log(JSON.stringify(toJSONobject));
Good luck!
edit: changed typeof to the correct .constructor. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor for more information on the constructor property for Objects.

This might be useful.
http://nanodeath.github.com/HydrateJS/
https://github.com/nanodeath/HydrateJS
Use hydrate.stringify to serialize the object and hydrate.parse to deserialize.

You can use a named function on the constructor.
MyClass1 = function foo(id, member) {
this.id = id;
this.member = member;
}
var myobject = new MyClass1("5678999", "text");
console.log( myobject.constructor );
//function foo(id, member) {
// this.id = id;
// this.member = member;
//}
You could use a regex to parse out 'foo' from myobject.constructor and use that to get the name.

Below is another way by which we can JSON data with JSON.stringify() function
var Utils = {};
Utils.MyClass1 = function (id, member) {
this.id = id;
this.member = member;
}
var myobject = { MyClass1: new Utils.MyClass1("5678999", "text") };
alert(JSON.stringify(myobject));

function ArrayToObject( arr ) {
var obj = {};
for (var i = 0; i < arr.length; ++i){
var name = arr[i].name;
var value = arr[i].value;
obj[name] = arr[i].value;
}
return obj;
}
var form_data = $('#my_form').serializeArray();
form_data = ArrayToObject( form_data );
form_data.action = event.target.id;
form_data.target = event.target.dataset.event;
console.log( form_data );
$.post("/api/v1/control/", form_data, function( response ){
console.log(response);
}).done(function( response ) {
$('#message_box').html('SUCCESS');
})
.fail(function( ) { $('#message_box').html('FAIL'); })
.always(function( ) { /*$('#message_box').html('SUCCESS');*/ });

I was having some issues using the above solutions with an "associative array" type object. These solutions seem to preserve the values, but they do not preserve the actual names of the objects that those values are associated with, which can cause some issues. So I put together the following functions which I am using instead:
function flattenAssocArr(object) {
if(typeof object == "object") {
var keys = [];
keys[0] = "ASSOCARR";
keys.push(...Object.keys(object));
var outArr = [];
outArr[0] = keys;
for(var i = 1; i < keys.length; i++) {
outArr[i] = flattenAssocArr(object[keys[i]])
}
return outArr;
} else {
return object;
}
}
function expandAssocArr(object) {
if(typeof object !== "object")
return object;
var keys = object[0];
var newObj = new Object();
if(keys[0] === "ASSOCARR") {
for(var i = 1; i < keys.length; i++) {
newObj[keys[i]] = expandAssocArr(object[i])
}
}
return newObj;
}
Note that these can't be used with any arbitrary object -- basically it creates a new array, stores the keys as element 0, with the data following it. So if you try to load an array that isn't created with these functions having element 0 as a key list, the results might be...interesting :)
I'm using it like this:
var objAsString = JSON.stringify(flattenAssocArr(globalDataset));
var strAsObject = expandAssocArr(JSON.parse(objAsString));

Related

Array of objects to database and back

I have array of functions/objects which I want to store to database, like this example:
function classPerson(firstName, lastName, activeStatus) {
this.firstName = firstName;
this.lastName = lastName;
this.activeStatus = activeStatus;
this.identify = function () {
return this.firstName + " " + this.lastName;
}
} // element
var persons = [];
var personsFromDatabase = [];
// define persons
var personOne = new classPerson('Bruce', 'Lee', true);
var personTwo = new classPerson('Chuck', 'Norris', false);
var personThree = new classPerson('Steven', ' Seagal', true);
// add persons to array
persons.push(personOne);
persons.push(personTwo);
persons.push(personThree);
// show persons data
for (var i = 0; i < persons.length; i++) {
alert(persons[i].identify());
}
// store to database
var toDatabase = JSON.stringify(persons);
alert(toDatabase);
// retrieve from database
var personsFromDatabase = JSON.parse(toDatabase);
// show persons data parsed from database
for (var i = 0; i < personsFromDatabase.length; i++) {
alert(personsFromDatabase[i].identify());
}
I transform persons array to string with JSON.stringify command and successfully store it to database.
When I load same string from database and transform back with JSON.parse to JS function/object I get list of simple objects (and error
TypeError: personsFromDatabase[i].identify is not a function
) instead of classPerson function/object and in console I can see that difference, like on picture below:
How can I achieve to get array of functions/objects instead of simple JS objects?
Fiddler link with example
You cannot save function in JSON, because function does not exist in JSON
But you can use second argument of stringify function to replace the function with value.
Like
var json = JSON.stringify(obj, function(key, value) {
if (typeof value === 'function') {
return value.toString();
} else {
return value;
}
});
As mentioned above, JSON has no functions as data types. You can only serialize strings, numbers, objects, arrays, and booleans (and null):
I have altered your example to provide a method to serialize and deserialize - which can be be as a basic template:
function ClassPerson(firstName, lastName, activeStatus) {
this.firstName = firstName;
this.lastName = lastName;
this.activeStatus = activeStatus;
this.identify = function () {
return this.firstName + " " + this.lastName;
}
} // element
ClassPerson.prototype.toJson = function() {
var data = {};
for(var prop in this) {
if(this.hasOwnProperty(prop) && (typeof this[prop] !== 'function')) {
data[prop] = this[prop];
}
}
return JSON.stringify(data);
};
ClassPerson.fromJson = function(json) {
var data = JSON.parse(json); // Parsing the json string.
if(data) {
var firstName = data.hasOwnProperty('firstName') ? data.firstName : "";
var lastName = data.hasOwnProperty('lastName') ? data.lastName : "";
var activeStatus = data.hasOwnProperty('activeStatus') ? data.activeStatus : "";
return new ClassPerson(firstName, lastName, activeStatus);
}
return {};
};
function serializeClassPersons(personArray) {
var serialised = [];
for (var i = 0; i < personArray.length; i++) {
serialised.push(persons[i].toJson());
};
return JSON.stringify(serialised);
};
function deserializeClassPersons(personsJsonString) {
var jsonStringArray = JSON.parse(personsJsonString); // this is an array
var persons = [];
for (var i = 0; i < jsonStringArray.length; i++) {
persons.push(ClassPerson.fromJson(jsonStringArray[i]));
};
return persons;
};
// add persons to array
var persons = [
new ClassPerson('Bruce', 'Lee', true),
new ClassPerson('Chuck', 'Norris', false),
new ClassPerson('Steven', ' Seagal', true)
];
var personsFromDatabase = [];
// show persons data
console.log('Using ClassPerson.identify():');
for (var i = 0; i < persons.length; i++) {
console.log(persons[i].identify());
};
console.log('Using ClassPerson toJson() and fromJson()');
for (var i = 0; i < persons.length; i++) {
var jsonPerson = persons[i].toJson();
console.log("json", jsonPerson);
var personFromJson = ClassPerson.fromJson(jsonPerson);
console.log("identify: ", persons[i].identify());
};
console.log('Serialize Persons Array to Json String');
var personsJson = serializeClassPersons(persons);
console.log(personsJson);
console.log('DeSerialize Json Persons String to Array');
var personsFromDatabase = deserializeClassPersons(personsJson);
console.log(personsFromDatabase);
The Output of this is:

Creating deep-nested objects in Javascript

When loading JSON from a server, I need to create objects. The objects do not always exist beforehand.Therefore I have to check that each level exists before adding a new level. Is there a better way to do this, then the following way:
var talkerId = commentDB.val().to;
var commentId = commentDB.val().id
if (!store.talkers.hasOwnProperty(talkerId)) {
store.talkers[talkerId] = {}
}
if (!store.talkers[talkerId].hasOwnProperty(comments)) {
store.talkers[talkerId] = { comments: {} };
}
if (!store.talkers[talkerId].comments.hasOwnProperty(commentId)) {
store.talkers[talkerId].comments[commentId] = {}
}
store.talkers[talkerId].comments[commentId].author = commentDB.val().author;
You cour reduce the keys by using the object an check if the key exist. if not create a new property with an empty object.
var dbValue = commentDB.val();
[dbValue.to, 'comments', dbValue.id].reduce(
(o, k) => o[k] = o[k] || {},
store.talkers
).author = commentDB.val().author;
Why don't you create a function
function checkAndCreateProperty(arr, baseVar) {
for(var i = 0; i < arr.length; i++) {
if (!baseVar.hasOwnProperty(arr[i])) {
baseVar[arr[i]] = {};
}
baseVar = baseVar[arr[i]];
}
}
checkAndCreateProperty(["talkerId", "comments", commentDB.val().id, commentDB.val().author], store.talkers)
After the suggestion of #31piy I went for the most simple solution:
using lodash _.set
var talkerId = commentDB.val().to;
var commentId = commentDB.val().id;
_.set(store.talkers, '[' + talkerId + '].comments[' + commentId + '].author', commentDB.val().author)

Need to change JSON property using a variable

c.key = "test";
a = {};
a.body = {};
a.body.interval={};
a.body.interval = c.key;
b = {};
b.body = {};
b.body.interval={};
b.body.interval = c.key;
c["key"]="sample";
return JSON.stringify(a);
I want to change all the values which are referred by mentioned variable in javascript.
Currently, this print
{"body":{"interval":"test"}}
I want to change properties referred by c.key.
I can not change individual properties of JSON as those are not fixed.
How can I change all the properties referred by an individual variable in javascript?
Not sure if this is exactly what you want but using a function instead of a variable can solve your problem. (since you can pass a replace function to stringify.
take a look at the following code:
c = {};
c.key = "test"
a = {};
a.body = {};
a.body.interval = function(){return c.key};
c["key"]="sample";
JSON.stringify(a, function (key, value) {
if (key == 'interval') {
return value();
} else {
return value;
}
});
c = {};
c.key = "test"
a = {};
a.body = {};
a.body.interval = function(){return c.key};
c["key"]="sample";
out = JSON.stringify(a, function (key, value) {
if (key == 'interval') {
return value();
} else {
return value;
}
});
console.log(out);

Javascript, implementing custom Object.Create

I need to implement inheritance tree in JavaScript where each node can have more than 1 parent. We have to implement Object.Create and Object.call methods on our own. We are specifically not allowed to use new keyword. Here is what I have so far:
var myObject = {
hash:0,
parents: [],
create: function(args){
//TODO check if not circular
if(args instanceof Array){
for(i=0;i<args.length;i++){
this.parents.push(args[i]);
}
}
return this;
},
call : function(fun,args){
//TODO: dfs through parents
return this[fun].apply(this,args);
},
}
var obj0 = myObject.create(null);
obj0.func = function(arg) { return "func0: " + arg; };
var obj1 = myObject.create([obj0]);
var obj2 = myObject.create([]);
obj2.func = function(arg) { return "func2: " + arg; };
var obj3 = myObject.create([obj1, obj2]);
var result = obj0.call("func", ["hello"]);
alert(result);
//calls the function of obj2 istead of obj0
The problem with this code is that I get a call to obj2's function instead of obj0's. I'm suspecting that create() function should not return this, but something else instead (create instance of itself somehow).
In your current solution, you are not actually creating a new object with your myObject.create() function, you are just using the same existing object and resetting it's parent array. Then, when you define .func() you are overriding that value, which is why func2: appears in your alert.
What you need to do is actually return a brand new object. returning this in your myObject.create() will just return your existing object, which is why things are getting overridden.
To avoid using the new keyword, you'll want to do either functional inheritance or prototypal inheritance. The following solution is functional inheritance:
function myObject (possibleParents) {
//create a new node
var node = {};
//set it's parents
node.parents = [];
//populate it's parents if passed in
if (possibleParents) {
if (possibleParents instanceof Array) {
for (var index = 0; index < possibleParents.length; index++) {
node.parents.push(possibleParents[index]);
}
} else {
node.parents.push(possibleParents);
};
}
//
node.call = function(fun,args) {
return this[fun].apply(this,args);
};
return node;
};
var obj0 = myObject();
obj0.func = function(arg) { return "func0: " + arg; };
var obj1 = myObject([obj0]);
var obj2 = myObject();
obj2.func = function(arg) { return "func2: " + arg; };
var obj3 = myObject([obj1, obj2]);
var result = obj0.call("func", ["hello"]);
alert(result); // this will successfully call "func0: " + arg since you created a new object
I managed fix this problem only by using function instead of variable.
function myObject () {
this.parents = [];
this.setParents = function(parents){
if(parents instanceof Array){
for(i=0;i<parents.length;i++){
this.parents.push(parents[i]);
}
}
};
this.call = function(fun,args) {
return this[fun].apply(this,args);
};
}
var obj0 = new myObject();
obj0.func = function(arg) { return "func0: " + arg; };
var obj2 = new myObject();
obj2.func = function(arg) { return "func2: " + arg; };
var result = obj0.call("func", ["hello"]);
alert(result);

Serialize and deserialize JS object

I lately was experimenting with the object serialization in JavaScript. I have already been looking through some of the questions concerning the serialization and deserialization of predefined object in Javascript, but I am looking for a more general solution. An example of this would be:
function anObject(){
var x = 1;
this.test = function(){return x;};
this.add = function(a){x+a;};
}
var x = new anObject();
x.add(2);
console.log(x.test());
>>> 3
var y = deserialize(serialize(x));
console.log(y.test());
>>> 3
Is there a way to serialize this object and deserialize it, such that the deserialized object still have access to the local variable x without the use of the prototype of that object (like in this solution)?
I have already tried by just storing the function as a string and evaluating it again, but then the state of an object can not be saved.
What you are trying to do is not possible without code introspection and code re-writing which I think is not a good idea. However, what about something like this?
function AnObject() {
var x = 1;
this.x = function () { return x; };
this.addToX = function (num) { x += num; };
this.memento = function () {
return { x: x };
};
this.restoreState = function (memento) {
x = memento.x;
};
}
var o = new AnObject();
o.addToX(2);
o.x(); //3
var serializedState = JSON.stringify(o.memento()),
o = new AnObject();
o.restoreState(JSON.parse(serializedState));
o.x(); //3
However, please note that having priviledged members comes at a great cost because you lose the benefits of using prototypes. For that reason I prefer not enforcing true privacy and rely on naming conventions such as this._myPrivateVariable instead (unless you are hiding members of a module).
Thanks for the responses. While the answer from plalx works perfectly for specific objects, I wanted to have something more general which just works for any object you throw at it.
Another solution one can use is something like this:
function construct(constructor, args, vars) {
function Obj() {
var variables = vars
return constructor.apply(this, args);
}
Obj.prototype = constructor.prototype;
return new Obj();
}
function addFunction(anObject, aFunction, variables) {
var objectSource = anObject.toString();
var functionSource = aFunction.toString();
objectSource = objectSource.substring(0,objectSource.length-1);
var functionName = functionSource.substring(9, functionSource.indexOf('('));
var functionArgs = functionSource.substring(functionSource.indexOf('('), functionSource.indexOf('{')+1);
var functionBody = functionSource.substring(functionSource.indexOf('{')+1, functionSource.length);
return objectSource + "this." + functionName + " = function" +
functionArgs + "var variables = " + variables + ";\n" + functionBody + "}";
}
function makeSerializable(anObject) {
var obj = JSON.stringify(anObject, function(key, val) {
return ((typeof val === "function") ? val+'' : val);
});
var variables = [];
while(obj.indexOf("var") > -1) {
var subString = obj.substring(obj.indexOf("var")+3, obj.length-1);
while (subString[0] == " ")
subString = subString.replace(" ", "");
var varEnd = Math.min(subString.indexOf(" "), subString.indexOf(";"));
var varName = subString.substring(0, varEnd);
variables.push(varName);
obj = obj.replace("var","");
}
var anObjectSource = addFunction(anObject,
function serialize(){
var vars = [];
console.log("hidden variables:" + variables);
variables.forEach(function(variable) {
console.log(variable + ": " + eval(variable));
vars += JSON.stringify([variable, eval(variable)]);
});
var serialized = [];
serialized.push(vars);
for (var func in this){
if (func != "serialize")
serialized.push([func, this[func].toString()]);
}
return JSON.stringify(serialized);
},
JSON.stringify(variables));
anObject = Function("return " + anObjectSource)();
var params = Array.prototype.slice.call(arguments);
params.shift();
return construct(anObject, params, variables);
}
This allows you to serialize all elements of any object, including the hidden variables. The serialize() function can then be replaced by a custom string representation for the hidden variables, which can be used when deserializing the string representation to the object.
usage:
function anObject(){
var x = 1;
var y = [1,2];
var z = {"name": "test"};
this.test = function(){return x;};
this.add = function(a){x+a;};
}
var test = makeSerializable(anObject)
test.serialize()
>>>["[\"x\",1][\"y\",[1,2]][\"z\",{\"name\":\"test\"}]",["test","function (){return x;}"],["add","function (a){x+a;}"]]

Categories

Resources