Skip to main content
Participating Frequently
June 30, 2009
Answered

xml or csv? when it comes to importing data...

  • June 30, 2009
  • 2 replies
  • 877 views

I need to import some dynamic values.  I was curious to know if xml or csv was better suited with javascript...  has anyone had a better experience with either of the formats?  Thanks again,

- Jacques

This topic has been closed for replies.
Correct answer xbytor2

If you're familiar at all with XML and your data has any complexity, use XML.

If the data is simply a table of values, use CSV.

If the data is an arbitrary set of key/value pairs, I prefer to use .ini files. They are easy to read/write in JS and by humans.

-X

2 replies

Participating Frequently
June 30, 2009

Thanks, managed to get it working using csv.

Inspiring
July 1, 2009

FWIW, here's some code from stdlib.js for parsing lines in a CSV file. This correctly handles quoted fields (with embedded commas) and just about everything else that I've been able to throw at it. Some of the code (the 'while (true)' loop, in particular) is there because I couldn't get the master RegExp expression quite right and had to handle some cases manually.

  var rexStr = '([^",]+)|"((?:[^"]|"")*)"|^,';

  var rexp = new RegExp(rexStr);

  function parseCSVLine(line) {

    var ch = ',';
    var parts = [];
    var res;

    while (line.length && (res = line.match(rexp)) != null) {
      if (res[1] || res[2]) {
        if (res[1]) {
          parts.push(res[1]);
        } else {
          parts.push(res[2].replace(/""/g, '"'));
        }
        line = line.slice(res[0].length + res.index);
        if (line[0] == ch) {
          line = line.slice(1);
        }
      } else {
        while (true) {
          if (line[0] == ch) {
            parts.push('');
            line = line.slice(1);
            continue;
          }
          if (line.startsWith('""')) {
            parts.push('');
            line = line.slice(2);
            if (line[0] == ch) {
              line = line.slice(1);
            }
            continue;
          }
          break;
        }
      }
    }
    return parts;
  }

xbytor2Correct answer
Inspiring
June 30, 2009

If you're familiar at all with XML and your data has any complexity, use XML.

If the data is simply a table of values, use CSV.

If the data is an arbitrary set of key/value pairs, I prefer to use .ini files. They are easy to read/write in JS and by humans.

-X