methods for converting an array to JSON using javascript

Our team is currently working on developing a PhoneGap application. We are in the process of extracting data from a CSV file and storing it into a SQLite database using the File API in PhoneGap.

function readDataUrl(file) {

    var reader = new FileReader();
    reader.onloadend = function(evt) {
        console.log("Read as data URL");
        console.log(evt.target.result);
    };
    reader.readAsDataURL(file);
}

function readAsText(file) {

    console.log('in readAsText'+file);

    var reader = new FileReader();
    reader.onloadend = function(evt) {
        ss=evt.target.result;
        alert(ss);
          console.log("Read as text");
        console.log(evt.target.result);
    };
    reader.readAsText(file);
}

We have successfully obtained the data, but unfortunately, it is not in the appropriate format for inserting into the SQLite database. We require JSON formatted data for this purpose.

Below is an example of the desired JSON format:

[  
    {  
        "FOC":1,
        "price":0,
        "customerid":"ARU005",
        "lineamount":0,
        "items":"W.D.M.W HERBAL 250Mx24",
        "tdate":"2015-4-7",
        "qty":8,
        "orderId":"Himansu16:23:20020",
        "umo":"CTN",
        "descriptions":"100mg",
        "bookorder":"ABCARU0052320"
    }
]

[  
    {  
        "TOTALAMOUNT":1000,
        "DISCOUNT":1,
        "NETAMOUNT ":900,
        "VAT":0,
        "GROSSAMOUNT ":900,
        "BOOKORDER":"ABCARUOO7451",
        "CUSTOMERID":"ARU007",
        "TODAYDATE":"2015-4-7"
    }
]

We are seeking guidance on how to convert the extracted data into JSON format from the CSV file. Any assistance would be greatly appreciated.

Answer №1

Implement the JSON.parse method in JavaScript:

Utilize your variable like so:

var jsonData = JSON.parse(evt.target.result);

For further reference, visit this resource.

If you receive an array as a result, you can utilize:

JSON.stringify(evt.target.result);

Answer №2

If you're struggling with parsing CSV data, check out this helpful Post.

Within the linked post, there are two approaches you can take:

  1. Utilize the jquery-csv Plugin for CSV file parsing.
  2. Your second option is to create a JavaScript function (Code provided here) specifically designed for parsing CSV files.

The choice is ultimately yours. It might require some exploration of these two options to ensure accurate results due to the unique and uncommon content of the CSV file mentioned in your initial question.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the sizing of all fonts following the switch in font styles

Seeking help for adjusting font-size across a responsive web page design using different font families. font-family:Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", serif; To achieve responsiveness, various media queries were applie ...

Is it beneficial to use both Bootstrap and ng-bootstrap together?

I have two modules in my angular website - "bootstrap" and "ng-bootstrap". Do I need both or just one? I am thinking of keeping only "ng-bootstrap" 4.0.0.0 and removing "bootstrap". Is this acceptable? What are the steps to remove "Bootstrap"? Can I simp ...

Nested AJAX call yields undefined value

In my Test.vue component, I have a method that is imported into my main.js. I can call its methods like this: this.$refs.test.testMethod(). There is another method in Test.vue called ajaxMethod(), which is defined as follows: function ajaxMethod(){ t ...

The controls for the Bootstrap carousel component do not have a clear appearance

Trying to implement a Bootstrap carousel component but facing an issue with the controls not appearing transparent like in the example provided in the Bootstrap documentation. Check out the code snippet: <div class="carousel slide" id="s ...

Redux action intensifies upon socket events

I have a Reactjs and Redux application that works well with axios. However, I would like to integrate socket.io into it. In my redux action, I tried the following: export const getOne = (id) => async dispatch => { socket.emit('getOne', i ...

Discover the secret to automatically calling a function every minute when the page is loaded!

Our team is currently developing a PhoneGap application with 4 pages. We are in need of posting the current latitude and longitude every minute to our server. Fortunately, we are familiar with how to post values to the server as well as how to retrieve the ...

Creating AngularJS variables with dependencies on integer values

Hello, I am a brand new developer and I am currently working on creating an expenses calculator. The goal is to have the sum of inputted integers from a table, each with a default value, become the integer value of another variable. However, I seem to be m ...

React Native: Error occurred while trying to install on virtual or physical device

For my final year project, I chose to use React Native for coding. However, I am facing an issue when trying to build and install it on virtual/physical devices, even though everything was working fine a month ago. Can someone help me figure out what' ...

In the event that you encounter various version formats during your work

Suppose I have a number in the format Example "1.0.0.0". If I want to increase it to the next version, it would be "1.0.0.1" By using the following regex code snippet, we can achieve this perfect result of incrementing the version to "1.0.0.1": let ver ...

Converting data into a hierarchical structure for a JSON file

Can someone assist me in parsing this specific file for the Gene Ontology (.obo)? I need guidance on how to accomplish this task. I am currently working on a project that involves creating a visualisation in D3. To achieve this, I require a JSON format "t ...

Determine the overall cost based on varying percentage increases for each step

I am currently working on developing a price estimation calculator. Here is the breakdown: For 1000 MTU, the price will be 0.035, resulting in a total of 35. For 2000 MTU, the price will be 0.034, making the total 67. For 3000 MTU, the price will be 0.03 ...

Updating the jQuery $ function to accommodate outdated codebases

After using stackoverflow as a valuable resource for years, I decided to join. I have a good grasp on JavaScript and noticed some questions that I could provide input on. As I delved into the platform, I realized the prevalence of jQuery. This prompted me ...

What is the best way to fulfill promises sequentially?

I'm currently facing a challenge with organizing promises in the correct order. I am developing a chat bot for DiscordApp using Node.js and have extensively searched both on this platform and Google. Despite trying Promise.all and an Async function, I ...

The webpack vue-loader throws an error message stating "unexpected token {" when processing a single-page .vue component

As a C# backend developer, I am venturing into the world of Vue.js. I typically work with Visual Studio 2017 + ASP.NET MVC (using it as an API + one layout) + Vue.js + Webpack. .vue single-page component files are loaded by vue-loader, while .js files a ...

What is the best way to download a vast number of files with nodejs?

I have a total of 25000 image links that I need to download to my local machine using the request package in nodejs. It successfully downloads up to 14000 to 15000, but then I start encountering errors. Error { Error: socket hang up at TLSSocket.onHa ...

Encountering ENOENT error when accessing view file in NodeJS and Express

I've encountered a strange issue with my nodeJS application after refactoring it. The app launches without any problems, the API responds correctly. However, when I attempt to access "/", I receive the following error: Error: ENOENT, stat '/view ...

How can I implement callback functions in joi validation?

Exploring the World of Coding I came across a code snippet online that caught my attention, but upon closer inspection, I realized it used Hapi/Joi which is now considered outdated. My question is how can I modify this code to work with Joi? app.post(&apo ...

Is there a way to link Dom $(this) from a different function?

Could you please review this code and advise on how I can bind $(this) in an external function within a DOM event? $(".adder").on("click", function(){ updateText(); }); function updateText(){ $(this).next(".mapper").html("Got You!"); } <scrip ...

Integrating AngularJS code into dynamically generated HTML using JavaScript

I am currently utilizing an outdated version of AngularJS (1.3). I have a page where I need to dynamically display different content based on database values. If the user interacts with the page and changes the database value, I want the displayed content ...

Tips for preventing the use of nested functions while working with AJAX?

Consecutively making asynchronous calls can be messy. Is there a cleaner alternative? The issue with the current approach is its lack of clarity: ajaxOne(function() { // do something ajaxTwo(function() { // do something ajaxThree() }); }); ...