从javascript对象数组生成json
我有一个包含很多属性和方法的javascript对象,我希望它被发送到一个php文件。为此,我希望将其转换为Json数据。 但我就是不明白应该如何使用json.stringify来实现这一点,因为这个复杂对象的类 这些对象看起来像这样。我有一个必须通过ajax发送的对象数组 此外,这个类还有一系列其他对象作为属性,以及一系列其他方法从javascript对象数组生成json,javascript,php,json,Javascript,Php,Json,我有一个包含很多属性和方法的javascript对象,我希望它被发送到一个php文件。为此,我希望将其转换为Json数据。 但我就是不明白应该如何使用json.stringify来实现这一点,因为这个复杂对象的类 这些对象看起来像这样。我有一个必须通过ajax发送的对象数组 此外,这个类还有一系列其他对象作为属性,以及一系列其他方法 var PhotoFile = function(clientFileHandle){ PhotoFile.count = PhotoFile.count
var PhotoFile = function(clientFileHandle){
PhotoFile.count = PhotoFile.count + 1;
this.specificClass = "no-" + PhotoFile.count;
this.checkbox = null;
this.attributes = [];
this.file = clientFileHandle;
this.fileExtension = null;
//meta data
this.meta = null;
this.orientation = null;
this.oDateTime = null;
this.maxWidth = 150;
this.maxHeight = 100;
//raw data
this.imgData = null;
this.imgDataWidth = null;
this.imgDataHeight = null;
this.checkSum1 = null;
this.checkSum2 = null;
//DOM stuff
this.domElement = null;
this.imgElement = null;
this.loadProgressBar = null;
this.uploadProgressBar = null;
this.imageContainer = null;
this.attributeContainer = null;
this.indexInGlobalArray = -1;
//flags
this.metaLoaded = false;
this.startedLoading = false;
this.finishedLoading = false;
this.needsUploading = true;
this.imageDisplayed = false;
//listeners
this.onFinishedLoading = function () {};
this.onFinishedUploading = function () {console.log('Called default end '+this.file.name)};
..... plus other methods.
}
您可以在对象上创建一个函数,该函数返回对象的可序列化表示形式 例如 请注意,使用泛型属性提取器算法会迫使您泄漏实现细节,因此会违反封装,因此,尽管使用此方法实现解决方案可能较短,但在某些情况下,这可能不是最好的方法
然而,限制内部泄漏通常可以做的一件事是实现属性。那么,当您执行
var obj=new PhotoFile(“…”)时会发生什么
然后JSON.stringify(obj)代码>?你得到了什么?如果这是你所期望的,你将无法序列化DOM节点和函数。您正在尝试发送哪些数据?顺便说一句,你的目标似乎做得太多了。。。我得到的错误如下:“Uncaught InvalidStateError:未能从'HTMLInputElement'读取'selectionDirection'属性”@普拉克斯,我知道,但我必须和那个班一起工作。您是否建议在该类上创建一个方法,该方法返回通过Json发送的所有属性的数组?或者创建另一个类来表示通过Json发送的数据?创建一个返回所有所需值的数组(或对象)(只要它们不是函数或DOM元素)的方法似乎是一个很好的解决方案。
function SomeObject() {
this.serializeThis = 'serializeThis';
this.dontSerializeThis = 'dontSerializeThis';
}
SomeObject.prototype.toSerializable = function () {
//You can use a generic solution like below
return subsetOf(this, ['serializeThis']);
//Or a hard-coded version
// return { serializeThis: this.serializeThis };
};
//The generic property extraction algorithm would need to be more complex
//to deep-filter objects.
function subsetOf(obj, props) {
return (props || []).reduce(function (subset, prop) {
subset[prop] = obj[prop];
return subset;
}, {});
}
var o = new SomeObject();
JSON.stringify(o.toSerializable()); //{"serializeThis":"serializeThis"}