BMi*_*ner 163 javascript parsing json prototype object
我知道如何解析JSON字符串并将其转换为JavaScript对象.您可以JSON.parse()在现代浏览器(和IE9 +)中使用.
这很好,但是如何将JavaScript对象转换为特定的 JavaScript对象(即使用某个原型)?
例如,假设你有:
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12
Run Code Online (Sandbox Code Playgroud)
同样,我不知道如何将JSON字符串转换为通用JavaScript对象.我想知道如何将JSON字符串转换为"Foo"对象.也就是说,我的对象现在应该有一个函数'test'和属性'a'和'b'.
更新 在做了一些研究后,我想到了......
Object.cast = function cast(rawObj, constructor)
{
var obj = new constructor();
for(var i in rawObj)
obj[i] = rawObj[i];
return obj;
}
var fooJSON = Object.cast({"a":4, "b": 3}, Foo);
Run Code Online (Sandbox Code Playgroud)
那会有用吗?
更新2017年5月:执行此操作的"现代"方式是通过Object.assign,但此功能在IE 11或更早版本的Android浏览器中不可用.
Eri*_*zen 101
当前答案包含大量手工或库代码.这不是必需的.
使用JSON.parse('{"a":1}')创建一个普通的对象.
使用其中一个标准化函数来设置原型:
Object.assign(new Foo, { a: 1 })Object.setPrototypeOf({ a: 1 }, Foo.prototype)Oli*_*ran 70
请参阅下面的示例(此示例使用本机JSON对象).我的更改在CAPITALS评论:
function Foo(obj) // CONSTRUCTOR CAN BE OVERLOADED WITH AN OBJECT
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
// IF AN OBJECT WAS PASSED THEN INITIALISE PROPERTIES FROM THAT OBJECT
for (var prop in obj) this[prop] = obj[prop];
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
// INITIALISE A NEW FOO AND PASS THE PARSED JSON OBJECT TO IT
var fooJSON = new Foo(JSON.parse('{"a":4,"b":3}'));
alert(fooJSON.test() ); //Prints 12
Run Code Online (Sandbox Code Playgroud)
Gab*_*mas 40
是否要添加JSON序列化/反序列化功能,对吧?然后看看这个:
你想实现这个目标:

toJson()是一种常规方法.
fromJson()是一个静态方法.
实施:
var Book = function (title, author, isbn, price, stock){
this.title = title;
this.author = author;
this.isbn = isbn;
this.price = price;
this.stock = stock;
this.toJson = function (){
return ("{" +
"\"title\":\"" + this.title + "\"," +
"\"author\":\"" + this.author + "\"," +
"\"isbn\":\"" + this.isbn + "\"," +
"\"price\":" + this.price + "," +
"\"stock\":" + this.stock +
"}");
};
};
Book.fromJson = function (json){
var obj = JSON.parse (json);
return new Book (obj.title, obj.author, obj.isbn, obj.price, obj.stock);
};
Run Code Online (Sandbox Code Playgroud)
用法:
var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}
var book = Book.fromJson (json);
alert (book.title); //prints: t
Run Code Online (Sandbox Code Playgroud)
注意:如果你愿意,你可以改变像所有的属性定义this.title,this.author等的var title,var author等等,并添加干将给他们完成UML定义.
BMi*_*ner 18
我发现有用的博客文章: 了解JavaScript原型
你可以搞乱Object的__proto__属性.
var fooJSON = jQuery.parseJSON({"a":4, "b": 3});
fooJSON.__proto__ = Foo.prototype;
Run Code Online (Sandbox Code Playgroud)
这允许fooJSON继承Foo原型.
我认为这不适用于IE,但至少从我读过的内容开始.
Luk*_*one 15
目前接受的答案对我不起作用。您需要正确使用 Object.assign() :
class Person {
constructor(name, age){
this.name = name;
this.age = age;
}
greet(){
return `hello my name is ${ this.name } and i am ${ this.age } years old`;
}
}
Run Code Online (Sandbox Code Playgroud)
您通常创建此类的对象:
let matt = new Person('matt', 12);
console.log(matt.greet()); // prints "hello my name is matt and i am 12 years old"
Run Code Online (Sandbox Code Playgroud)
如果您有一个 json 字符串需要解析到 Person 类中,请像这样执行:
let str = '{"name": "john", "age": 15}';
let john = JSON.parse(str); // parses string into normal Object type
console.log(john.greet()); // error!!
john = Object.assign(Person.prototype, john); // now john is a Person type
console.log(john.greet()); // now this works
Run Code Online (Sandbox Code Playgroud)
我在问题中遗漏了什么,或者为什么没有人提到自2011年以来的reviver参数JSON.parse?
以下是解决方案的简单代码:https: //jsfiddle.net/Ldr2utrr/
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse(`{"a":4, "b": 3}`, function(key,value){
if(key!=="") return value; //logic of course should be more complex for handling nested objects etc.
let res = new Foo();
res.a = value.a;
res.b = value.b;
return res;
});
// Here you already get Foo object back
alert(fooJSON.test() ); //Prints 12
Run Code Online (Sandbox Code Playgroud)
PS:你的问题很混乱:>> 那很好,但是如何将JavaScript对象转换为特定的JavaScript对象(即使用某个原型)? 与标题相矛盾,您询问JSON解析,但引用的段落询问JS运行时对象原型替换.
| 归档时间: |
|
| 查看次数: |
149388 次 |
| 最近记录: |