Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Zotero Script for Wikidata Lookup
// Zotero script look up selected items in Wikidata and
// check whether the DOI can be found there. If results
// are found then the QIDs are saved in the corresponding
// items in the extra field. Some warnings are given for the
// other cases; thus watch the Zotero error console as well
// during execution of the script. [CC0]
var items = Zotero.getActiveZoteroPane().getSelectedItems();
var map = [];
for (let item of items) {
if (item.getField("DOI")) {
map[item.getField("DOI").toUpperCase()] = { id: item.id }
}
else {
Zotero.log("Skipped id " + item.id + " because no DOI");
}
}
var doiString = '"' + Object.keys(map).join('" "').toUpperCase() + '"';
var queryUrl = "https://query.wikidata.org/sparql?query=";
var query = encodeURIComponent('SELECT * WHERE { VALUES ?doi { ' + doiString + '} ?item wdt:P356 ?doi . }');
var suffix = "&format=json";
var url = queryUrl + query+ suffix;
Zotero.log("URL " + url);
await Zotero.HTTP.doGet(url, function (obj) {
data = JSON.parse(obj.responseText);
Zotero.log(obj.responseText);
var results = data.results.bindings;
for (let result of results) {
let doi = result.doi.value;
let qid = result.item.value.replace("http://www.wikidata.org/entity/", "");
map[doi].qid = qid;
let item = Zotero.Items.get(map[doi].id);
let extra = item.getField("extra") || "";
let extraLines = extra.split("\n");
let skip = false;
for (line of extraLines) {
if (line.startsWith("QID:") && line.endsWith(qid)) {
skip = true;
}
}
if (!skip) {
item.setField("extra", extra + "\nQID: " + qid);
item.saveTx();
}
else {
Zotero.log("Skipped id " + map[doi].id + " because QID " + qid + " already there");
}
}
if (results.length == 0) {
Zotero.log("Nothing found on Wikidata.");
}
});
return map;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment