导出到 CSV 和导入到 IndexedDB 时的额外引号

Extra quotes when exporting to CSV and importing to IndexedDB

我正在导出和导入内部嵌套数组的对象数组,在此过程中使用 ngCSV、loDash 和 PapaParse。

数组如下所示:

[
    {
        arrival:"15.34.59",
        cancelled:"",
        comments:[{message: "test", commenttime: "15.34", $$hashKey: "object:552"}]
        date:"27/09/2016"
    },
    {
        arrival:"16.32.59",
        cancelled:true,
        comments:[]
        date:"27/09/2016"
    }
]

当我点击以下按钮时:

<button 
    ng-csv="commenttoJson(filteredRecords)" 
    csv-header="['date', 'comments', 'arrival', 'cancelled']" 
    filename="{{ createCsvFilename(dates) }}">
        Download
</button>

触发此函数并下载文件:

$scope.commenttoJson = function(filteredRecords){
    return _.map(filteredRecords, function(record){
        return _.extend({}, record, {comments: JSON.stringify(record.comments)});
    }); 
}

生成的文件如下所示:

date,comments,arrival,cancelled
27/09/2016,"[{""message"":""testing"",""commenttime"":""14.52"",""$$hashKey"":""object:50""}]",14.52.29,,
27/09/2016,[],,TRUE

然后我继续使用这些函数导入它:

$scope.onFileSelect = function ($files) {
  Papa.parse($files[0], {
    header: true,
    skipEmptyLines: true,
    complete: function(results, $files,err) {
      if (err) {
          console.log('err ', err);
      }
      $scope.parseddata = results.data;
    }
  });
};

$scope.importData = function () {
  $indexedDB.openStore('records', function(store){
    store.insert($scope.parseddata).then(function(e){
      store.getAll().then(function(record) {  
        $scope.recordlist = record;
        console.log($scope.recordlist);
        $('.import-data').modal('hide');
        $scope.deleted = false;
      });
    });
  });
};

问题是它完美地导入了所有内容,除了评论,现在看起来像下面这样,显然前端无法正确读取:

[
    {
        arrival:"15.34.59",
        cancelled:"",
        comments:"[{"message":"test","commenttime":"15.34","$$hashKey":"object:552"}]"
        date:"27/09/2016"
    }, (...)

显然在这个过程中我遗漏了一些东西,因为所有额外的引号都会弄乱我的代码。

关于如何解决这个问题有什么想法吗?

编辑并修复

$scope.onFileSelect = function ($files) {
  Papa.parse($files[0], {
    header: true,
    skipEmptyLines: true,
    complete: function(results, $files,err) {
        if (err) {
            console.log('err ', err);
        }

    $scope.filteredRecordsToImport = _.map(results.data, function(item){
        return _.extend(item, {comments: item.comments ? JSON.parse(item.comments) : []});
    });
    console.log($scope.filteredRecordsToImport);

    }
  });
};

显然我不得不重新解析 JSON 以反转字符串化并删除数组中的额外引号!

$scope.onFileSelect = function ($files) {
  Papa.parse($files[0], {
    header: true,
    skipEmptyLines: true,
    complete: function(results, $files,err) {
        if (err) {
            console.log('err ', err);
        }

    $scope.filteredRecordsToImport = _.map(results.data, function(item){
        return _.extend(item, {comments: item.comments ? JSON.parse(item.comments) : []});
    });
    console.log($scope.filteredRecordsToImport);

    }
  });
};

显然我不得不重新解析 JSON 以反转字符串化并删除数组中的额外引号!