Converting JSON data to CSV format with JavaScript

I have been attempting to convert a JSON object to CSV using JavaScript, but the results are not as expected.

UPDATE: The JSON object is stored in a variable, and every time I try to access 'list', it returns as undefined. Is there a way to access the list through a variable?

Here is the JSON object I am working with:

{
  "type": "success",
  "message": "success",
  "list": [
    {
      "ExtensionData": {},
      "Address": "Baler",
      "fld_test": "testMendoza",
      "CocNumber": "1000000001",
      "CustomerName": "test",
      "IssueDate": "\\/Date(1584892800000)\\/",
      "ProductName": "testProd",
      "TransactionId": 1
    },
    { ...additional JSON objects }
  ],
  "totalPage": 0
}

I have tried using the following JavaScript function for the conversion, but the CSV file ends up empty:

function ConvertToCSV(objArray) {
    alert("start json to csv conversion");
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';
        for (var index in array[i]) {
            if (line != '') line += ','

            line += array[i][index];
        }

        str += line + '\r\n';
        //
    }
    return str;
}

The JSON code has been validated by online formatters, so I am curious if there is an issue with the JavaScript function?

Answer №1

If you're looking for an insightful answer, check out this resource -

Additionally, here's a concise example for your reference:

const data = {"type":"success","message":"success","list":[{"ExtensionData":{},"Address":"Baler","fld_test":"test Mendoza","CocNumber":"1000000001","CustomerName":"test","IssueDate":"/Date(1584892800000)/","ProductName":"testProd","TransactionId":1},{"ExtensionData":{},"Address":"Baler","fld_test":"ff","CocNumber":"1000000002","CustomerName":"test","IssueDate":"/Date(1584892800000)/","ProductName":"testProd","TransactionId":2},{"ExtensionData":{},"Address":"Baler","fld_test":"c","CocNumber":"1000000003","CustomerName"... [Truncated for brevity]

Answer №2

const dataToConvert = {"type":"success","message":"success","items":[{"ExtensionData":{},"Location":"Baler","fld_test":"test Mendoza","CocNumber":"1000000001","CustomerName":"test","IssueDate":"/Date(1584892800000)/","ProductName":"testProd","TransactionId":1}],"totalPage":0}
function convertToCSV(objectArray) {
    var csvString = '';
    var arrayOfObjects = objectArray.items;
    for (var i = 0; i < arrayOfObjects.length; i++) {
        var line = '';
        for (var key in arrayOfObjects[i]) {
          if(typeof (arrayOfObjects[i][key]) != 'object'){
            if (line != '') line += ','
              line += arrayOfObjects[i][key];
          }
        }
        csvString += line + '\r\n';

    }

    return csvString;
}

var csvOutput = this.convertToCSV(dataToConvert);
console.log('Converted CSV Output:', csvOutput);

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

Encountering a NodeJS crash when executing MySQL queries

Exploring NodeJS for the first time and experimenting with MySQL. Successfully retrieving content from the database to display on my page (/test01). Encountering a crash when attempting to fetch values from the database in order to store them in a cookie ...

failure to properly assign a property during model update in mongoose

My BaseSchema contains logic that should set values for two properties when a new Model is created: schema.pre("save", function (next) { if (!schema.isNew) { this.createDate = new Date(); this.createBy = "kianoush"; } next(); }); If updating, ...

Jquery not functioning properly for show and hide feature

I'm new to using Jquery and JqueryUI. I have a div named front, which I want to initially display on window load and then hide it by sliding after a delay of 5500 milliseconds. However, I'm encountering errors in the jquery.min.js file. The HTML ...

The complexity of utilizing the map() function in React causes confusion

While delving into React, I stumbled upon this interesting code snippet: {this.state.sections.map(({title, imageUrl, id, size}) => ( <MenuItem key={id} title={title} imageUrl={imageUrl} size={size}/> ))} I'm intrigued by the use of destruc ...

Retrieve information through an AJAX or JavaScript request and use it to fill the selected plugin's multiple selection feature

I have searched everywhere for a solution to this problem, but I haven't been able to find any helpful resources. I apologize in advance if this question has been asked before. What I need to do is to display the data from a JSON object that is fetch ...

ExpressJS route handler encounters an error due to undefined 'this' reference

teamList.js class teamListCtrl { constructor() { this.data = "example"; } fetch(response, request) { console.log("DISPLAY ! ", JSON.stringify(this)); } } module.exports = new teamListCtrl(); //singleton router.js var express = require( ...

Having trouble with jQuery on my webpage

Looking for assistance with a technical issue I'm facing... I am currently working with AngularJS and have integrated jQuery into my project. However, I've encountered an issue where the jQuery code is not functioning as expected on the HTML pag ...

achieving initial value to show upon page load

I'm trying to set a default value that is visible when the page loads. My goal is to have the first button always displayed by default in the "display-donation" div whenever someone visits the form. Currently, when the page loads, 10 is highlighted ...

Angular: When $scope variable is modified, a blank page issue arises

In my Angular application, I have a template called viewAll.html that is displayed after clicking on a link. This template fetches data via AJAX using scope variables. However, I encountered an issue where updating these scope variables through AJAX cause ...

How can I add a channel to a category using await(discord.js)?

Having trouble organizing a new channel within a category. The .setParent(categoryID) method seems to only work with existing channels, causing an issue when I attempt to execute my code. Take a look at the code snippet below: client.on("message" ...

Struggling to adjust the timeout to exceed 60 seconds

I have been attempting to set a timeout for 120 seconds or more, but no matter what I try, the requests are timing out after only 60 seconds. Things I have tried include: $.ajax({ url: URL, timeout: 120000, success: function(html){ co ...

Transferring a Variable from Arduino to JavaScript

Is there a simple way to pass an Arduino variable as a JS variable? Let's say we have an integer Arduino variable called sensorData: int sensorData = analogRead(sensorPin); How can we transfer this value to a JavaScript variable? client.println(&quo ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

What are the steps to creating a JSON String?

Encountering an issue with parsing JSON data, as shown in the following example: String s = "{\n" + "\t\"foo1\": {\n" + "\t\t\"array1\": [\n" + "\t\t\t[1, \"One& ...

Adding a stylesheet dynamically in Angular 2: A step-by-step guide

Is there a method to dynamically add a stylesheet URL or <style></style> in Angular2? For instance, if the variable isModalOpened is set to true, I want to apply certain CSS styles to elements outside of my root component, such as the body or ...

Wcf Service does not define Angular JS methods

I am utilizing a WCF Service within an AngularJS application. The WCF Service is functional, and I am attempting to display a list of user records from a SQL database. However, upon running the application, I encountered the following errors: angular.js: ...

Is there a way to overlay a 'secret' grid on top of a canvas that features a background image?

I am currently working on developing an HTML/JS turn-based game, where I have implemented a canvas element using JavaScript. The canvas has a repeated background image to resemble a 10x10 squared board. However, I want to overlay a grid on top of it so tha ...

Removing the year data and converting the month in JavaScript

Currently, I am utilizing the following code snippet to parse XML in Javascript: $this(find).text() When this code runs within an HTML environment, the output for the date from the XML data appears as: 2014-04-07T19:48:00 My objective is to format it l ...

Problem with jQuery's UI autocomplete functionality

Implementing jQ UI Autocomplete with multiple values Below is how my function is structured: mailto_input.bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "autocomplete" ).menu.active ) { ...

Rule for jQuery validation based on variables

I am facing an issue with validation of login asynchronously in my HTML form using the jQuery Validation Plugin. I would like to trigger a request for login validity on blur, and validate it upon receiving a response. Below is the code snippet: var login ...