Public
Edited
Apr 11, 2023
2 forks
Importers
10 stars
Insert cell
Insert cell
viewof data = dataInput({
value: [{ name: "Your Initial Data" }],
delimiter: ',', // Optional
format: "auto" // Optional, one of MongoExport, JSON, CSV, CSVNoAutoType
})
Insert cell
data
Insert cell
function dataInput({
value = [],
initialValue = undefined,
accept = "",
delimiter = ",",
format = "auto"
} = {}) {
if (initialValue !== undefined && value.length === 0) {
value = initialValue;
}

const processFile = (data) => {
if (format === "auto") {
try {
return loadJSON(data, delimiter);
} catch {
console.log("Failed with json");
}
try {
return loadMongoExport(data);
} catch {
console.log("Failed with MongoExport");
}
try {
return loadCSVAutoType(data, delimiter);
} catch {
console.log("Failed with CSV AutoType");
}
try {
return loadCSV(data);
} catch {
console.log("Failed with CSV");
}
return value;
} else {
switch (format.toUpperCase()) {
case "JSON":
try {
return loadJSON(data, delimiter);
} catch {
console.log("Failed with json");
return initialValue;
}
case "MONGOEXPORT":
try {
return loadMongoExport(data);
} catch {
console.log("Failed with MongoExport");
return value;
}
case "CSV":
try {
return loadCSVAutoType(data, delimiter);
} catch {
console.log("Failed with CSV AutoType");
return value;
}
case "CSVNOAUTO":
try {
return loadCSV(data);
} catch {
console.log("Failed with CSV");
return value;
}
}
}
};

const form = html`<form><input name=i type="file" accept="${accept}">`;
form.i.onchange = async () => {
form.value = await Files.text(
form.i.multiple ? form.i.files : form.i.files[0]
).then(processFile);
form.dispatchEvent(new Event("input"), { bubbles: true });
};
form.value = value;
return form;
}
Insert cell
loadMongoExport = (data) => {
console.log("Trying Mongo export");
const res = [];
for (let row of data.split("\n")){
if(row === "") { continue; }
try{
row = JSON.parse(row);
res.push(row);
} catch(e3){
break;
}
}
if (res.length>0) {
return res;
} else {
throw "Error parsing MongoExport";
}
}
Insert cell
loadJSON = (data) => {
console.log("Trying JSON");
return JSON.parse(data);
}
Insert cell
loadCSVAutoType = (data, delimiter) => {
console.log("Trying CSV autotype");
return d3.dsvFormat(delimiter).parse(data, d3.autoType);
}
Insert cell
loadCSV = (data, delimiter) => {
console.log("Trying CSV");
return d3.dsvFormat(delimiter).parse(data);
}
Insert cell
d3 = require("d3")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more