In the sample below, i have serialized an object which is including an array. But this is turned into an object type when serialized. Therefore a normal ".length" of the property will fail.
var serialize = require('node-serialize');
//Creating an object including an array
var company = {
name: 'John Does Farming',
yearFounded: 1995,
listOfEmployees: ['Mike', 'Sue', 'Martin']
};
//JSON.stringify() the object
var JSONstringified=JSON.stringify(company);
//Serializing the object
var serializedObject = serialize.serialize(company);
//Printing the objects out
console.log('Using JSON.stringify() - showing "listOfEmployees" as Array:');
console.log(JSONstringified);
console.log('\nUsing serialize() - showing "listOfEmployees" as Object:');
console.log(serializedObject);
//Unserializing it
var unserializedObject = serialize.unserialize(serializedObject);
//Trying to fetch the list of employees which fails since the Array is serialized to an Object
console.log('\nlistOfEmployees.length:');
console.log(unserializedObject.listOfEmployees.length);
This is the result:
Using JSON.stringify() - showing "listOfEmployees" as Array:
{"name":"John Does Farming","yearFounded":1995,"listOfEmployees":["Mike","Sue","Martin"]}
Using serialize() - showing "listOfEmployees" as Object:
{"name":"John Does Farming","yearFounded":1995,"listOfEmployees":{"0":"Mike","1":"Sue","2":"Martin"}}
listOfEmployees.length:
undefined
In the sample below, i have serialized an object which is including an array. But this is turned into an object type when serialized. Therefore a normal ".length" of the property will fail.
This is the result: