I'm going to write currency converter with JavaScript. Currency will be updated daily in CSV files. I want to figure out how to get values from CSV and the best (efficient) way to store them in application. Thank you!
-
1Can you use a server side language?Pekka– Pekka2011-03-29 10:41:23 +00:00Commented Mar 29, 2011 at 10:41
-
no, i cant. but still curious how to do this with using it.Petya petrov– Petya petrov2011-03-29 10:46:48 +00:00Commented Mar 29, 2011 at 10:46
-
you should be able to fetch the CSV file through Ajax, and then split it yourself. It would however be more convenient to do the parsing in a server side language, and have that language send JSON dataPekka– Pekka2011-03-29 10:51:01 +00:00Commented Mar 29, 2011 at 10:51
3 Answers
A simple way is to do:
<script type="text/javascript" src="conversion_table.js"></script>
<script type="text/javascript" src="converter.js"></script>
The conversion table is just a JavaScript file defining a single object:
var conversion_table =
{
"USD-GBP": 1.2,
:
:
};
It is more efficient to use JavaScript objects instead of having to parse a CSV file whenever your user loads your page.
2 Comments
Use the jQuery-CSV plugin
With jquery-csv, transforming CSV to JavaScript data structure becomes very simple.
Using the data:
val1,"value 2",val3,val4
"val,1",val2,val3,
Do:
var array = $.csv.toArray(csv);
Outputs:
[
["val1","value 2","val3","val4"],
["val,1","val2","val3",""]
]
If you want the entries mapped to key:value pairs, just call the toObjects() function instead.
Using the data:
foo,bar,baz,fuzz
val1,"value 2",val3,val4
"val,1",val2,val3,
Do:
var dict = $.csv.toObjects(csv);
Outputs:
[
{foo:"val1",bar:"value 2",baz:"val3",fuzz:"val4"},
{foo:"val,1",bar:"val2",baz:"val3",fuzz:""}
]
If you need to allow cross-domain requests, this library will also work in Node.js. After the data is converted, assign it to a variable and send a response with the data encoded as 'text/javascript' (Ie JSONP).
Disclaimer: I'm the author of jquery-csv.
Comments
I'd suggest using a JQuery plugin to convert your CSV data into an array.
This one seems like it ought to do the trick: http://plugins.jquery.com/project/csv