CSVToJSON.mjs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * @author n1474335 [n1474335@gmail.com]
  3. * @copyright Crown Copyright 2018
  4. * @license Apache-2.0
  5. */
  6. import Operation from "../Operation.mjs";
  7. import OperationError from "../errors/OperationError.mjs";
  8. import Utils from "../Utils.mjs";
  9. /**
  10. * CSV to JSON operation
  11. */
  12. class CSVToJSON extends Operation {
  13. /**
  14. * CSVToJSON constructor
  15. */
  16. constructor() {
  17. super();
  18. this.name = "CSV to JSON";
  19. this.module = "Default";
  20. this.description = "Converts a CSV file to JSON format.";
  21. this.infoURL = "https://wikipedia.org/wiki/Comma-separated_values";
  22. this.inputType = "string";
  23. this.outputType = "JSON";
  24. this.args = [
  25. {
  26. name: "Cell delimiters",
  27. type: "binaryShortString",
  28. value: ","
  29. },
  30. {
  31. name: "Row delimiters",
  32. type: "binaryShortString",
  33. value: "\\r\\n"
  34. },
  35. {
  36. name: "Format",
  37. type: "option",
  38. value: ["Array of dictionaries", "Array of arrays"]
  39. }
  40. ];
  41. }
  42. /**
  43. * @param {string} input
  44. * @param {Object[]} args
  45. * @returns {JSON}
  46. */
  47. run(input, args) {
  48. const [cellDelims, rowDelims, format] = args;
  49. let json, header;
  50. try {
  51. json = Utils.parseCSV(input, cellDelims.split(""), rowDelims.split(""));
  52. } catch (err) {
  53. throw new OperationError("Unable to parse CSV: " + err);
  54. }
  55. switch (format) {
  56. case "Array of dictionaries":
  57. header = json[0];
  58. return json.slice(1).map(row => {
  59. const obj = {};
  60. header.forEach((h, i) => {
  61. obj[h] = row[i];
  62. });
  63. return obj;
  64. });
  65. case "Array of arrays":
  66. default:
  67. return json;
  68. }
  69. }
  70. }
  71. export default CSVToJSON;