diff --git a/chrome/content/zotero/xpcom/data/item.js b/chrome/content/zotero/xpcom/data/item.js index 68e488bc5..e3fb3dba9 100644 --- a/chrome/content/zotero/xpcom/data/item.js +++ b/chrome/content/zotero/xpcom/data/item.js @@ -4918,6 +4918,192 @@ Zotero.Item.prototype.serialize = function(mode) { return arr; } +/** + * Serializes Zotero Item into Zotero web server API JSON format + * + * @param {Object} options + * mode {String}: [new|full|patch] "new" is default. "full" mode includes all + * fields even if empty. "patch" returns only fields that are different from + * those in patchBase + * patchBase {Object}: Item in API JSON format to be compared to in + * "patch" mode. Required if "patch" mode is specified + */ +Zotero.Item.prototype.toJSON = function(options) { + if (this.id || this.key) { + if (!this._primaryDataLoaded) { + this.loadPrimaryData(true); + } + + if (this.id) { + if (!this._itemDataLoaded) this._loadItemData(); + if (this.isRegularItem() && !this._creatorsLoaded) this._loadCreators(); + if (!this._relatedItemsLoaded) this._loadRelatedItems(); + } + } + + if (this.hasChanged()) { + throw new Error("Cannot generate JSON from changed item"); + } + + options = options || {}; + let mode = options.mode || 'new'; + let patchBase = options.patchBase; + + if (mode == 'patch') { + if (!patchBase) { + throw new Error('Cannot use "patch" mode if patchBase not provided'); + } + } + else if (patchBase) { + Zotero.debug('Zotero.Item.toJSON: ignoring provided patchBase in "' + mode + '" mode', 2); + } + + let obj = { + key: this.key || false, + version: 1, + itemType: Zotero.ItemTypes.getName(this.itemTypeID), + tags: [], + collections: [], + relations: {} + }; + + // Type-specific fields + for (let i in this._itemData) { + let val = '' + this.getField(i); + if (val !== '' || mode == 'full') { + let name = Zotero.ItemFields.getName(i); + if (name == 'version') { + // Changed in API v3 to avoid clash with 'version' above + // Remove this after https://github.com/zotero/zotero/issues/670 + name = 'versionNumber'; + } + + obj[name] = val; + } + } + + if (this.isRegularItem()) { + // Creators + obj.creators = []; + let creators = this.getCreators(); + for (let i=0; i