将 JSON 反序列化为 JAVASCRIPT 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8039534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
deserialize JSON to JAVASCRIPT object
提问by Kalamarico
i have a question to deserialize JSON text to an javascript object, i test jquery and yui library, i have this class:
我有一个将 JSON 文本反序列化为 javascript 对象的问题,我测试了 jquery 和 yui 库,我有这个类:
function Identifier(name, contextId) {
this.name = name;
this.contextId = contextId;
}
Identifier.prototype.setName = function(name) {
this.name = name;
}
Identifier.prototype.getName = function() {
return this.name;
}
Identifier.prototype.setContextId = function(contexId) {
this.contextId= contexId;
}
Identifier.prototype.getContextId = function() {
return this.contextId;
}
and i have this JSON:
我有这个 JSON:
{
"Identifier": {
"name":"uno",
"contextId":"dos"}
}
I want to the parse create an Identifier object, my problem is that this sentences:
我想解析创建一个标识符对象,我的问题是这句话:
var obj = jQuery.parseJSON('{"Identifier": { "name":"uno","contextId":"dos"}}');
or
或者
var obj2 = JSON.parse('{"Identifier": { "name":"uno","contextId":"dos"}}');
Dont work, the var obj and obj2 aren't an Identifier object, how can i parse this? Thanks
不工作,var obj 和 obj2 不是标识符对象,我该如何解析?谢谢
This question is not the duplicate, because it was made 5 years before than the question that Michael marks as duplicated
这个问题不是重复的,因为它比迈克尔标记为重复的问题早 5 年提出
采纳答案by Alex Turpin
You could create a function that initializes those objects for you. Here's one I quickly drafted:
您可以创建一个为您初始化这些对象的函数。这是我很快起草的一份:
function parseJSONToObject(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)
return null;
var obj = new window[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);