Get usable array from csvtojson









up vote
1
down vote

favorite
1












I've seen code examples of using csvtojson, but each one simply outputs the result using console.log(). The following code creates a variable named 'json', but I don't see how I can use this outside of the function creating it. How can I export the variable 'json' for use outside of the function that is creating it?:



const csvFilePath='<path to csv file>'
const csv=require('csvtojson')

csv().fromFile(csvFilePath,function(err,result)

if(err)
console.log("An Error Has Occured");
console.log(err);


var json = result; // I want to use this var outside of this function.
console.log(json);
);


I was really hoping that it would be as simple as writing something like:



const dataArray = csv().fromFile(csvFilePath);


But, dataArray doesn't contain my data, but instead appears to be an object with parameters about the data.



Any clues will be greatly appreciated!










share|improve this question

















  • 2




    Possible duplicate of How do I return the response from an asynchronous call?
    – Lux
    Nov 10 at 21:05






  • 1




    Very close: const jsonArray = await csv().fromFile(csvFilePath); npmjs.com/package/csvtojson#from-csv-file-to-json-array
    – Jonathan
    Nov 10 at 22:31















up vote
1
down vote

favorite
1












I've seen code examples of using csvtojson, but each one simply outputs the result using console.log(). The following code creates a variable named 'json', but I don't see how I can use this outside of the function creating it. How can I export the variable 'json' for use outside of the function that is creating it?:



const csvFilePath='<path to csv file>'
const csv=require('csvtojson')

csv().fromFile(csvFilePath,function(err,result)

if(err)
console.log("An Error Has Occured");
console.log(err);


var json = result; // I want to use this var outside of this function.
console.log(json);
);


I was really hoping that it would be as simple as writing something like:



const dataArray = csv().fromFile(csvFilePath);


But, dataArray doesn't contain my data, but instead appears to be an object with parameters about the data.



Any clues will be greatly appreciated!










share|improve this question

















  • 2




    Possible duplicate of How do I return the response from an asynchronous call?
    – Lux
    Nov 10 at 21:05






  • 1




    Very close: const jsonArray = await csv().fromFile(csvFilePath); npmjs.com/package/csvtojson#from-csv-file-to-json-array
    – Jonathan
    Nov 10 at 22:31













up vote
1
down vote

favorite
1









up vote
1
down vote

favorite
1






1





I've seen code examples of using csvtojson, but each one simply outputs the result using console.log(). The following code creates a variable named 'json', but I don't see how I can use this outside of the function creating it. How can I export the variable 'json' for use outside of the function that is creating it?:



const csvFilePath='<path to csv file>'
const csv=require('csvtojson')

csv().fromFile(csvFilePath,function(err,result)

if(err)
console.log("An Error Has Occured");
console.log(err);


var json = result; // I want to use this var outside of this function.
console.log(json);
);


I was really hoping that it would be as simple as writing something like:



const dataArray = csv().fromFile(csvFilePath);


But, dataArray doesn't contain my data, but instead appears to be an object with parameters about the data.



Any clues will be greatly appreciated!










share|improve this question













I've seen code examples of using csvtojson, but each one simply outputs the result using console.log(). The following code creates a variable named 'json', but I don't see how I can use this outside of the function creating it. How can I export the variable 'json' for use outside of the function that is creating it?:



const csvFilePath='<path to csv file>'
const csv=require('csvtojson')

csv().fromFile(csvFilePath,function(err,result)

if(err)
console.log("An Error Has Occured");
console.log(err);


var json = result; // I want to use this var outside of this function.
console.log(json);
);


I was really hoping that it would be as simple as writing something like:



const dataArray = csv().fromFile(csvFilePath);


But, dataArray doesn't contain my data, but instead appears to be an object with parameters about the data.



Any clues will be greatly appreciated!







javascript node.js csvtoarray






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 20:57









Tony Guinta

365148




365148







  • 2




    Possible duplicate of How do I return the response from an asynchronous call?
    – Lux
    Nov 10 at 21:05






  • 1




    Very close: const jsonArray = await csv().fromFile(csvFilePath); npmjs.com/package/csvtojson#from-csv-file-to-json-array
    – Jonathan
    Nov 10 at 22:31













  • 2




    Possible duplicate of How do I return the response from an asynchronous call?
    – Lux
    Nov 10 at 21:05






  • 1




    Very close: const jsonArray = await csv().fromFile(csvFilePath); npmjs.com/package/csvtojson#from-csv-file-to-json-array
    – Jonathan
    Nov 10 at 22:31








2




2




Possible duplicate of How do I return the response from an asynchronous call?
– Lux
Nov 10 at 21:05




Possible duplicate of How do I return the response from an asynchronous call?
– Lux
Nov 10 at 21:05




1




1




Very close: const jsonArray = await csv().fromFile(csvFilePath); npmjs.com/package/csvtojson#from-csv-file-to-json-array
– Jonathan
Nov 10 at 22:31





Very close: const jsonArray = await csv().fromFile(csvFilePath); npmjs.com/package/csvtojson#from-csv-file-to-json-array
– Jonathan
Nov 10 at 22:31













2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted










The problem is that fromFile is asynchronous, and once you have called async code, you live in the callback.



The module doesn't seem to provide a sync alternative. Your options are:



  • Continue your program logic inside the callback:



csv().fromFile(csvFilePath,function(err,result)

if(err)
console.log("An Error Has Occured");
console.log(err);


var json = result;
console.log(json);

// Continue your logic here
// .....
// .....
);


  • Use async/await

You seem to be using an older version of csvtojson, so you might need to upgrade it to use this:



(async () => 

var jsons = await csv().fromFile(csvFilePath);
console.log(jsons);

)()
.catch((err) =>
console.log(err);
);


Basically this wraps your code inside an async function. Inside it, you can use the return value of fromFile if you use the await keyword.



  • Use a different module that supports sync loading or even do the parsing yourself.





share|improve this answer





























    up vote
    0
    down vote













    csvJSON function with functional map



    var csvJSON = function(csv)
    var lines = csv.split("n");
    var result = ;
    var headers = lines[0].split(",");
    lines.map(function(line, indexLine)
    if (indexLine < 1) return // Jump header line
    var obj = ;
    var currentline = line.split(",");
    headers.map(function(header, indexHeader)
    obj[header] = currentline[indexHeader];
    )
    result.push(obj);
    )
    result.pop(); // remove the las`enter code here`t item because undefined values
    return result; // JavaScript object






    share|improve this answer




















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













       

      draft saved


      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243335%2fget-usable-array-from-csvtojson%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      1
      down vote



      accepted










      The problem is that fromFile is asynchronous, and once you have called async code, you live in the callback.



      The module doesn't seem to provide a sync alternative. Your options are:



      • Continue your program logic inside the callback:



      csv().fromFile(csvFilePath,function(err,result)

      if(err)
      console.log("An Error Has Occured");
      console.log(err);


      var json = result;
      console.log(json);

      // Continue your logic here
      // .....
      // .....
      );


      • Use async/await

      You seem to be using an older version of csvtojson, so you might need to upgrade it to use this:



      (async () => 

      var jsons = await csv().fromFile(csvFilePath);
      console.log(jsons);

      )()
      .catch((err) =>
      console.log(err);
      );


      Basically this wraps your code inside an async function. Inside it, you can use the return value of fromFile if you use the await keyword.



      • Use a different module that supports sync loading or even do the parsing yourself.





      share|improve this answer


























        up vote
        1
        down vote



        accepted










        The problem is that fromFile is asynchronous, and once you have called async code, you live in the callback.



        The module doesn't seem to provide a sync alternative. Your options are:



        • Continue your program logic inside the callback:



        csv().fromFile(csvFilePath,function(err,result)

        if(err)
        console.log("An Error Has Occured");
        console.log(err);


        var json = result;
        console.log(json);

        // Continue your logic here
        // .....
        // .....
        );


        • Use async/await

        You seem to be using an older version of csvtojson, so you might need to upgrade it to use this:



        (async () => 

        var jsons = await csv().fromFile(csvFilePath);
        console.log(jsons);

        )()
        .catch((err) =>
        console.log(err);
        );


        Basically this wraps your code inside an async function. Inside it, you can use the return value of fromFile if you use the await keyword.



        • Use a different module that supports sync loading or even do the parsing yourself.





        share|improve this answer
























          up vote
          1
          down vote



          accepted







          up vote
          1
          down vote



          accepted






          The problem is that fromFile is asynchronous, and once you have called async code, you live in the callback.



          The module doesn't seem to provide a sync alternative. Your options are:



          • Continue your program logic inside the callback:



          csv().fromFile(csvFilePath,function(err,result)

          if(err)
          console.log("An Error Has Occured");
          console.log(err);


          var json = result;
          console.log(json);

          // Continue your logic here
          // .....
          // .....
          );


          • Use async/await

          You seem to be using an older version of csvtojson, so you might need to upgrade it to use this:



          (async () => 

          var jsons = await csv().fromFile(csvFilePath);
          console.log(jsons);

          )()
          .catch((err) =>
          console.log(err);
          );


          Basically this wraps your code inside an async function. Inside it, you can use the return value of fromFile if you use the await keyword.



          • Use a different module that supports sync loading or even do the parsing yourself.





          share|improve this answer














          The problem is that fromFile is asynchronous, and once you have called async code, you live in the callback.



          The module doesn't seem to provide a sync alternative. Your options are:



          • Continue your program logic inside the callback:



          csv().fromFile(csvFilePath,function(err,result)

          if(err)
          console.log("An Error Has Occured");
          console.log(err);


          var json = result;
          console.log(json);

          // Continue your logic here
          // .....
          // .....
          );


          • Use async/await

          You seem to be using an older version of csvtojson, so you might need to upgrade it to use this:



          (async () => 

          var jsons = await csv().fromFile(csvFilePath);
          console.log(jsons);

          )()
          .catch((err) =>
          console.log(err);
          );


          Basically this wraps your code inside an async function. Inside it, you can use the return value of fromFile if you use the await keyword.



          • Use a different module that supports sync loading or even do the parsing yourself.






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 11 at 9:55

























          answered Nov 11 at 9:43









          mihai

          22.8k73968




          22.8k73968






















              up vote
              0
              down vote













              csvJSON function with functional map



              var csvJSON = function(csv)
              var lines = csv.split("n");
              var result = ;
              var headers = lines[0].split(",");
              lines.map(function(line, indexLine)
              if (indexLine < 1) return // Jump header line
              var obj = ;
              var currentline = line.split(",");
              headers.map(function(header, indexHeader)
              obj[header] = currentline[indexHeader];
              )
              result.push(obj);
              )
              result.pop(); // remove the las`enter code here`t item because undefined values
              return result; // JavaScript object






              share|improve this answer
























                up vote
                0
                down vote













                csvJSON function with functional map



                var csvJSON = function(csv)
                var lines = csv.split("n");
                var result = ;
                var headers = lines[0].split(",");
                lines.map(function(line, indexLine)
                if (indexLine < 1) return // Jump header line
                var obj = ;
                var currentline = line.split(",");
                headers.map(function(header, indexHeader)
                obj[header] = currentline[indexHeader];
                )
                result.push(obj);
                )
                result.pop(); // remove the las`enter code here`t item because undefined values
                return result; // JavaScript object






                share|improve this answer






















                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  csvJSON function with functional map



                  var csvJSON = function(csv)
                  var lines = csv.split("n");
                  var result = ;
                  var headers = lines[0].split(",");
                  lines.map(function(line, indexLine)
                  if (indexLine < 1) return // Jump header line
                  var obj = ;
                  var currentline = line.split(",");
                  headers.map(function(header, indexHeader)
                  obj[header] = currentline[indexHeader];
                  )
                  result.push(obj);
                  )
                  result.pop(); // remove the las`enter code here`t item because undefined values
                  return result; // JavaScript object






                  share|improve this answer












                  csvJSON function with functional map



                  var csvJSON = function(csv)
                  var lines = csv.split("n");
                  var result = ;
                  var headers = lines[0].split(",");
                  lines.map(function(line, indexLine)
                  if (indexLine < 1) return // Jump header line
                  var obj = ;
                  var currentline = line.split(",");
                  headers.map(function(header, indexHeader)
                  obj[header] = currentline[indexHeader];
                  )
                  result.push(obj);
                  )
                  result.pop(); // remove the las`enter code here`t item because undefined values
                  return result; // JavaScript object







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 10 at 22:57









                  Mehar

                  1




                  1



























                       

                      draft saved


                      draft discarded















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243335%2fget-usable-array-from-csvtojson%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      27

                      Top Tejano songwriter Luis Silva dead of heart attack at 64

                      Category:Rhetoric