Skip to content

Instantly share code, notes, and snippets.

@zuphilip
Last active December 16, 2021 10:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zuphilip/aa9f59271fcb0807fb20c7d0110d26e4 to your computer and use it in GitHub Desktop.
Save zuphilip/aa9f59271fcb0807fb20c7d0110d26e4 to your computer and use it in GitHub Desktop.
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 you may want to 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")] = { id: item.id };
map[item.getField("DOI").toUpperCase()] = { id: item.id };
}
else {
item.addTag("no-doi");
// look for items with the tag "no-doi" and possibly assign some color to the tag
item.saveTx();
Zotero.log("Skipped id " + item.id + " because no DOI");
}
}
var doiString = '"' + Object.keys(map).join('" "') + '"';
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