When reading a Json object array and creating the csv file the first column is emply from the second record and foward

时间:2015-10-29 15:43:43

标签: javascript arrays json node.js csv

I have this JSON Object array (excerpt). In my Javascript I am creating a csv with the values I wanted with an iteration function. The problem is that the first record of the csv is created correctly but from the second record and forward is creating an empty first column. It has a comma as the first character and I don't know what in my logic is causing it. Can you help? See the code below:

"recs-count": 139, 
"gps-recs": [
    { 
        "RecId": 40020551513, 
        "City": "New Port Richey", 
        "Country": "USA", 
        "County": "PASCO", 
        "State": "FL", 
        "Street": "1546 Amaryllis ct.", 
        "ZipCode": "34655", 
        "CurrentOdometer": 12161, 
        "Heading": 0, 
        "Latitude": 28.181690, 
        "Longitude": -82.658420, 
        "SpeedMph": 0, 
        "SpeedLimitMph": 25, 
        "Status": "Stopped", 
        "StatusDuration": "1.05:00:00", 
        "PrimaryLandmarkName": "Max's home", 
        "CurrentHardmountEvent": null, 
        "UtcTimeTag": "2013-11-28T05:23:34", 
        "UserTimeTag": "2013-11-28T00:23:34", 
        "UserInfo": { 
            "UserId": 201274, 
            "UserNumber": "22", 
            "UserName": "Max's Car" 
        } 
    },
    { 
        "RecId": 40020551610, 
        "City": "New Port Richey", 
        "Country": "USA", 
        "County": "PASCO", 
        "State": "FL", 
        "Street": "1546 Amaryllis ct.", 
        "ZipCode": "34655", 
        "CurrentOdometer": 12161, 
        "Heading": 0, 
        "Latitude": 28.181690, 
        "Longitude": -82.658410,

Code:

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  var result = JSON.parse(body)['gps-recs'];
    console.log(result);
    console.log(Object.keys(result).length);
  //console.log(body);
  buildCSV(result); 

});
function buildCSV(result) {
    // loop runs result.length times
    for (i = 0; i < Object.keys(result).length; i++) {

            csvFile.push(result[i].UserInfo.UserNumber + ',' + result[i].UtcTimeTag + ',' + result[i].Latitude + ',' + result[i].Longitude + ',' + result[i].Speed + ',' + result[i].Heading + '\r\n' );
            console.log(csvFile[i]);
        };

    fs.writeFile('file.csv', csvFile, function(err) {
       if (err) throw err;
       console.log('file saved');
    });
};

This is the file created (txt viewed):

2169266287,2015-10-27T04:00:05,25.796945,-80.255766,undefined,100,
,2164309328,2015-10-27T04:00:20,42.224414,-83.347603,undefined,0,
,2162029911,2015-10-27T04:00:46,41.500245,-81.681383,undefined,0,
,2164328304,2015-10-27T04:01:19,42.238847,-83.32803,undefined,0,
,2164309328,2015-10-27T04:01:28,42.22442,-83.347484,undefined,0,
,2162029911,2015-10-27T04:01:46,41.500245,-81.681383,undefined,0,
,2164328304,2015-10-27T04:02:23,42.23782,-83.328911,undefined,0,
,2164309328,2015-10-27T04:02:39,42.224411,-83.34745,undefined,0,
,2162029911,2015-10-27T04:02:46,41.50021,-81.681347,undefined,140,
,2164328304,2015-10-27T04:03:12,42.238956,-83.325409,undefined,0,
,2169655749,2015-10-27T04:03:24,25.797042,-80.260972,undefined,136,
,2162029911,2015-10-27T04:03:46,41.50021,-81.681347,undefined,0,
,2164309328,2015-10-27T04:03:49,42.224419,-83.347445,undefined,0,
,2162029911,2015-10-27T04:04:46,41.50021,-81.681347,undefined,0,
,2164309328,2015-10-27T04:05:05,42.22442,-83.347456,undefined,0,
,2164328304,2015-10-27T04:05:29,42.238716,-83.327105,undefined,211,
,2162029911,2015-10-27T04:05:46,41.50021,-81.681347,undefined,0,
,2164309328,2015-10-27T04:06:28,42.22441,-83.347477,undefined,0,
,2164328304,2015-10-27T04:06:32,42.239021,-83.32724,undefined,256,

This is how the JSON Object looks like after parsing: enter image description here

The working code is as follows: I had to change the array with the CSV format data into a string (variable). The fs.write module needed a string, not an array. That's why the data was changed after going through fs write module. Thank you all for your help!

var request = require("request");
var fs = require ('fs');
var csvFile = "";
var options = { method: 'GET',
  url: 'URL',
   };

request(options, function (error, response, body) {
  if (error) throw new Error(error);

  var result = JSON.parse(body)['gps-recs'];

    console.log(Object.keys(result).length);
    console.log(result.length);

  buildCSV(result); 

});
function buildCSV(result) {
    // loop runs result.length times

    for (var i = 0; i < result.length; i++) {

    csvFile = csvFile.concat(result[i].UserInfo.UserNumber + ',' + result[i].UtcTimeTag + ',' + result[i].Latitude + ',' + result[i].Longitude + ',' + result[i].Speed + ',' + result[i].Heading + '\r\n');

        };
    console.log(csvFile);
    fs.writeFile('file.csv', csvFile, function(err) {
      //fs.writeFile('file.csv', csvFile, function(err) {
       if (err) throw err;
       console.log('file saved');
    });
};

2 个答案:

答案 0 :(得分:2)

看起来你正在构建一个名为cvsFile的数组,其中数组中的每个元素代表文件中的一行。然后,您将数组传递给writeFile方法。 writeFile方法需要一个字符串或Buffer。 writeFile方法通过使用“,”作为分隔符连接元素,将数组转换为字符串。我相信你需要自己创建字符串,方法是使用空字符串“”作为分隔符连接元素。然后,您可以将该字符串传递给writeFile方法。例如......

<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener("DOMContentLoaded", init);
function init(){
    var dropbox = document.getElementById('dropbox');
    dropbox.addEventListener('dragover', drag.over);
    dropbox.addEventListener('drop', drag.drop);
}
var drag = {
    "over": function(e){
        e.preventDefault();
    },
    "drop": function(e){
        e.preventDefault();
        console.log(e); //NO FILES SHOWN
        console.log(e.dataTransfer.files); //FILES in FileList Object
    }   
};  
</script>
<style>
body{
    margin: 0 !important;
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
}
#dropbox{
    height: 400px;
    width: 400px;
    align-self: center;
    background-color: #0089C4;
    border-radius: .3em;
    border: 1px dashed black;
    -webkit-box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40);
    box-shadow: 0px 2px 7px rgba(0, 0, 0, 0.40);
}
</style>
</head>
<body>
    <div id="dropbox"></div>    
</body> 
</html>

答案 1 :(得分:1)

看起来问题是buildCSV方法正在迭代对象上定义的成员而不是集合中的记录数。

您想要定义您的方法:

function buildCSV(result) {
    // loop runs result.length times
    for (i = 0; i < result.length; i++) { // **this was changed**

            csvFile.push(result[i].UserInfo.UserNumber + ',' + result[i].UtcTimeTag + ',' + result[i].Latitude + ',' + result[i].Longitude + ',' + result[i].Speed + ',' + result[i].Heading + '\r\n' );
            console.log(csvFile[i]);
        };

    fs.writeFile('file.csv', csvFile, function(err) {
       if (err) throw err;
       console.log('file saved');
    });
};

您使用的Object.Keys属性实质上是通过对象上定义的所有属性进行枚举,而看起来您想循环遍历数组。