我有一个带有很多属性和方法的 JavaScript 对象,我希望将其发送到 php 文件。为此,我想将其转换为 Json 数据。
但由于复杂对象的类,我只是无法理解应该如何使用 json.stringify 来执行此操作。
对象看起来像这样。我有一个必须通过 ajax 发送的对象数组。
此外,此类还具有其他对象数组作为属性,以及一堆其他方法。
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.
}
最佳答案
您可以在对象上创建一个函数,该函数返回对象的可序列化表示形式。
例如
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"}
请注意,使用通用属性提取器算法会迫使您泄漏实现细节,从而违反封装,因此尽管使用此方法实现解决方案可能更短,但在某些情况下可能不是最好的方法。
但是,通常可以做的一件事是限制内部泄漏,即实现属性 getters .
关于javascript - 从 JavaScript 对象数组中生成 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26662833/