0

I am trying to create a dictionary in javascript from a csv file with four columns. I want the key to be the content in the column A and the value to be a list containing the contents of columns B:D.

For example, the csv file looks like this: A B C D "face.jpg" "Old" "Female" "Happy" "face2.jpg" "Old" "Male" "Happy"

And I would like the dictionary to look like this:

faceDict = { face.jpg : ["Old", "Female", "Happy], face2.jpg : [ "Old", "Male", "Happy] }

Is there any way to do this in javascript? I would really appreciate any help, thanks!

Audrey Liu
  • 35
  • 1
  • 4
  • 1
    Have you tried anything to accomplish this? – basic Jan 23 '19 at 18:15
  • It's only possible with file access, so you won't be doing this from the client-side web. It would have to be local or server side. Anyway, you have to show what you've tried. A CSV file is just a string separated by two common delimiters( commas and new lines). – zfrisch Jan 23 '19 at 18:16
  • Have you checked the solution described in this question? https://stackoverflow.com/questions/33401523/convert-csv-file-to-json-dictionary – Griggs Jan 23 '19 at 18:18
  • @zfrisch it might actually be possible client side – yaakov Jan 23 '19 at 18:28
  • @YaakovAinspan Maybe - to be honest the file API is something I'm not incredibly familiar with, but I think you'd have to either upload or retrieve from a fetch request. – zfrisch Jan 23 '19 at 18:34
  • @basic I've done this in python with this code: with open('image_names.csv', mode='r') as infile: reader = csv.reader(infile) stimdict = dict((rows[0],rows[1:4]) for rows in reader) I've also tried in javascript to do something like this just to get the first column of my csv file, but it seems to be bugging out: Facestim = d3.csvParse("C:\Users\sl553\Box\Task_Switch_2Tasks\image_names.csv", function(data) { console.log(data[0]); }); – Audrey Liu Jan 23 '19 at 18:45
  • @zfrisch, I know there is a way that you can get the content of a file on the client side, like for example previewing an image prior to uploading it. I don't know precisely how this would apply in this case, but it makes sense that it would. – yaakov Jan 23 '19 at 22:36

1 Answers1

0

I got this to work using Chrome on Windows (with some unnecessary steps.)

A csv has these contents:

 "1" "b" "c" "d"
 "2" "f" "g" "h"

Open the file with a text editor and paste the contents into a script, then surround the string with backticks:

const csv = `1,b,c,d
2,f,g,h`;

Here's the full script:

<html>
<script>

const csv = `1,b,c,d
2,f,g,h`;

// Replaces newline characters with commas
const csvModified = csv.replace(/\n/g, ",");

// Converts the string to an array 
const arr = csvModified.split(",");

//Separates the keys and values into their own arrays (assuming every 4th item is a key) 
let keys = [], vals = [];
for(i = 0; i < arr.length; i++){
  if(i % 4 == 0){ keys.push(arr[i]); }
  else { vals.push(arr[i]); }
}

// Makes a javascript object (i.e. a dictionary) from the two arrays
const dict = {};
for(i = 0; i < keys.length; i++){
  localVals = vals.splice(0,3); // Extracts the first three items as a new array
  dict[keys[i]] = localVals; // Adds a property (named for the key) to the object
}

// Prints the object to the browser console
console.log(dict);

</script>
</html>

The object looks like:

{
  1: ["b", "c", "d"]
  2: ["f", "g", "h"]
}
Cat
  • 4,141
  • 2
  • 10
  • 18
  • Hello! Thank you for this answer. It looks like it's on the verge of working but I'm just running into the following syntax error when I run this code on Chrome: Uncaught SyntaxError: Octal escape sequences are not allowed in template strings. – Audrey Liu Jan 24 '19 at 02:28
  • Hello! Thank you for this answer. It looks like it's on the verge of working but I'm just running into the following syntax error when I run this code on Chrome: Uncaught SyntaxError: Octal escape sequences are not allowed in template strings. – Audrey Liu Jan 24 '19 at 03:52
  • Thanks. If you liked my answer, please consider marking it as accepted. I've never heard of the "Octal escape sequences" error, but here's a reference that might help: `mathiasbynens.be/notes/javascript-escapes`. I believe "template mode" refers to using backtick characters to allow multi-line strings. If you can determine which part of the string javascript is interpreting as an octal character, you might be able to store that part of the string in a variable and then re-insert it into its place in the template like `\`normal text ${varHoldingOctalCharacters} more normal text\`` Good luck! – Cat Jan 24 '19 at 06:03