Example JavaScript code to parse CSV data

前端 未结 12 1720
梦谈多话
梦谈多话 2020-11-21 07:58

Where could I find some JavaScript code to parse CSV data?

12条回答
  •  悲&欢浪女
    2020-11-21 08:23

    jQuery-CSV

    It's a jQuery plugin designed to work as an end-to-end solution for parsing CSV into JavaScript data. It handles every single edge case presented in RFC 4180, as well as some that pop up for Excel/Google spreadsheet exports (i.e., mostly involving null values) that the specification is missing.

    Example:

    track,artist,album,year

    Dangerous,'Busta Rhymes','When Disaster Strikes',1997

    // Calling this
    music = $.csv.toArrays(csv)
    
    // Outputs...
    [
      ["track", "artist", "album", "year"],
      ["Dangerous", "Busta Rhymes", "When Disaster Strikes", "1997"]
    ]
    
    console.log(music[1][2]) // Outputs: 'When Disaster Strikes'
    

    Update:

    Oh yeah, I should also probably mention that it's completely configurable.

    music = $.csv.toArrays(csv, {
      delimiter: "'", // Sets a custom value delimiter character
      separator: ';', // Sets a custom field separator character
    });
    

    Update 2:

    It now works with jQuery on Node.js too. So you have the option of doing either client-side or server-side parsing with the same library.

    Update 3:

    Since the Google Code shutdown, jquery-csv has been migrated to GitHub.

    Disclaimer: I am also the author of jQuery-CSV.

提交回复
热议问题