2

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!

3
  • 1
    Can you use a server side language? Commented Mar 29, 2011 at 10:41
  • no, i cant. but still curious how to do this with using it. Commented 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 data Commented Mar 29, 2011 at 10:51

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

IMHO, It is always better to perform such operations at server end, ie, converting csv to js object literals.
True. Since that file is in JS format, the only rational place for it to be created is on the server.
1

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

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.