从对象数组生成json javascript


Make json from array of objects javascript

我有一个javascript对象,它有很多属性和方法,我希望它被发送到php文件中。为此,我希望将其转换为Json数据

但是,由于复杂对象的类,我不明白该如何使用json.stringfy来实现这一点。

这些对象看起来是这样的。我有一组必须通过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"}

请注意,使用通用属性提取器算法会迫使您泄露实现细节,从而违反封装,因此,尽管使用此方法实现解决方案可能会更短,但在某些情况下,这可能不是最佳方式。

然而,通常可以做一件事来限制内部泄漏,那就是实现属性getter。