Deserialize Json To Javascript Object
i have a question to deserialize JSON text to an javascript object, i test jquery and yui library, i have this class: function Identifier(name, contextId) { this.name = name;
Solution 1:
You could create a function that initializes those objects for you. Here's one I quickly drafted:
functionparseJSONToObject(str) {
var json = JSON.parse(str);
var name = null;
for(var i in json) { //Get the first property to act as name
name = i;
break;
}
if (name == null)
returnnull;
var obj = newwindow[name]();
for(var i in json[name])
obj[i] = json[name][i];
return obj;
}
This creates an object of the type represented by the name of the first attribute, and assigns it's values according to the attributes of the object of the first attribute. You could use it like that:
var identifier = parseJSONToObject('{"Identifier": { "name":"uno","contextId":"dos"}}');
console.log(identifier);
Post a Comment for "Deserialize Json To Javascript Object"