无法将 .json 文件从 CSV 下载到 JSON 转换并且无法将 JSON 转换为 CSV
Posted
技术标签:
【中文标题】无法将 .json 文件从 CSV 下载到 JSON 转换并且无法将 JSON 转换为 CSV【英文标题】:Cannot download .json file from CSV to JSON Conversion and Cannot convert JSON to CSV 【发布时间】:2019-02-03 14:51:51 【问题描述】:我的将 CSV 转换为 JSON 数据的算法有效,但是当我单击“下载 JSON”时,它会给我一个 CSV 文件。有谁知道是什么问题?
此外,“转换为 CSV”按钮没有输出任何内容!
即使我包含了 Highcharts 代码,您也无需关注它。
有谁知道如何解决这个问题?代码在这里(一些代码属于 JSFiddle 的 Sturtevant。感谢他):
function CSVToArray(strData, strDelimiter)
// Check to see if the delimiter is defined. If not,
// then default to comma.
strDelimiter = (strDelimiter || ",");
// Create a regular expression to parse the CSV values.
var objPattern = new RegExp((
// Delimiters.
"(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
// Quoted fields.
"(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
// Standard fields.
"([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
// Create an array to hold our data. Give the array
// a default empty first row.
var arrData = [[]];
// Create an array to hold our individual pattern
// matching groups.
var arrMatches = null;
// Keep looping over the regular expression matches
// until we can no longer find a match.
while (arrMatches = objPattern.exec(strData))
// Get the delimiter that was found.
var strMatchedDelimiter = arrMatches[1];
// Check to see if the given delimiter has a length
// (is not the start of string) and if it matches
// field delimiter. If id does not, then we know
// that this delimiter is a row delimiter.
if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter))
// Since we have reached a new row of data,
// add an empty row to our data array.
arrData.push([]);
// Now that we have our delimiter out of the way,
// let's check to see which kind of value we
// captured (quoted or unquoted).
if (arrMatches[2])
// We found a quoted value. When we capture
// this value, unescape any double quotes.
var strMatchedValue = arrMatches[2].replace(
new RegExp("\"\"", "g"), "\"");
else
// We found a non-quoted value.
var strMatchedValue = arrMatches[3];
// Now that we have our value string, let's add
// it to the data array.
arrData[arrData.length - 1].push(strMatchedValue);
// Return the parsed data.
return (arrData);
function CSV2JSON(csv)
var array = CSVToArray(csv);
var objArray = [];
for (var i = 1; i < array.length; i++)
objArray[i - 1] = ;
for (var k = 0; k < array[0].length && k < array[i].length; k++)
var key = array[0][k];
objArray[i - 1][key] = array[i][k]
var json = JSON.stringify(objArray);
var str = json.replace(/,/g, ",\r\n");
return str;
$("#convert").click(function()
var csv = $("#csv").val();
var json = CSV2JSON(csv);
$("#json").val(json);
);
$("#download").click(function()
var csv = $("#csv").val();
var json = CSV2JSON(csv);
window.open("data:text/json;charset=utf-8," + escape(json))
);
function JSON2CSV(objArray)
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var line = '';
if ($("#labels").is(':checked'))
var head = array[0];
if ($("#quote").is(':checked'))
for (var index in array[0])
var value = index + "";
line += '"' + value.replace(/"/g, '""') + '",';
else
for (var index in array[0])
line += index + ',';
line = line.slice(0, -1);
str += line + '\r\n';
for (var i = 0; i < array.length; i++)
var line = '';
if ($("#quote").is(':checked'))
for (var index in array[i])
var value = array[i][index] + "";
line += '"' + value.replace(/"/g, '""') + '",';
else
for (var index in array[i])
line += array[i][index] + ',';
line = line.slice(0, -1);
str += line + '\r\n';
return str;
$("#convert").click(function()
var json = $.parseJSON($("#json").val());
var csv = JSON2CSV(json);
$("#csv").val(csv);
);
$("#download").click(function()
var json = $.parseJSON($("#json").val());
var csv = JSON2CSV(json);
window.open("data:text/csv;charset=utf-8," + escape(csv))
);
var myJson = ["category":1,"guestValue":0,"visits":23,"category":2,"guestValue":96.6,"visits":45,"category":3,"guestValue":73.2,"visits":65,"category":4,"guestValue":60.3,"visits":85,"category":5,"guestValue":52.5,"visits":105,"category":6,"guestValue":46.6,"visits":125,"category":7,"guestValue":41.4,"visits":144,"category":8,"guestValue":37.5,"visits":163,"category":9,"guestValue":34.4,"visits":179,"category":10,"guestValue":31.9,"visits":199,"category":"11-17","guestValue":25.4,"visits":258,"category":"18-28","guestValue":17,"visits":394,"category":"29+","guestValue":9.7,"visits":847];
var category = [];
var guestValue = [];
var visits = [];
for (i=0; i < myJson.length; i++)
guestValue.push(myJson[i].guestValue);
visits.push(myJson[i].visits);
category.push(myJson[i].category);
Highcharts.chart('container',
chart:
type: 'bar'
,
title:
text: null,
align: 'center',
verticalAlign: 'bottom',
,
xAxis:
categories: category,
title:
text: 'Visits Per Customer (TTM)'
,
,
yAxis:
min: 0,
gridLineWidth: 0,
minorGridLineWidth: 0,
title:
text: 'Average Return Rate Overall: 64 Days',
y: 10
,
labels:
overflow: 'justify'
,
tooltip:
headerFormat: '<span style="font-size:10px">point.key</span><table>',
pointFormat: '<tr><td style="color:series.color;padding:0">series.name: </td>' +
'<td style="padding:0"><b>point.y:.0f </b></td></tr>',
footerFormat: '</table>',
shared: true,
usehtml: true
,
plotOptions:
bar:
dataLabels:
enabled: true,
,
legend:
layout: 'horizontal',
align: 'right',
verticalAlign: 'top',
x: -25,
y: 5,
width: 280,
floating: true,
borderWidth: 1,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: true
,
credits:
enabled: false
,
series: [
name: 'Q1 / 18 (TTM) Annual Guest Value',
data: guestValue,
color: 'grey',
// label color
dataLabels:
style:
color: 'grey'
,
name: 'Days Between 1st and 2nd Visits',
data: visits,
color: 'green',
// label color
dataLabels:
style:
color: 'green'
]
);
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<!--alasql library-->
<script src="https://cdn.jsdelivr.net/alasql/0.3/alasql.min.js"></script>
<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>
<script>
angular.module('app', []).controller('downloader', function($scope)
// json data to be exported
$scope.data = ["category":1,"guestValue":0,"visits":23,"category":2,"guestValue":96.6,"visits":45,"category":3,"guestValue":73.2,"visits":65,"category":4,"guestValue":60.3,"visits":85,"category":5,"guestValue":52.5,"visits":105,"category":6,"guestValue":46.6,"visits":125,"category":7,"guestValue":41.4,"visits":144,"category":8,"guestValue":37.5,"visits":163,"category":9,"guestValue":34.4,"visits":179,"category":10,"guestValue":31.9,"visits":199,"category":"11-17","guestValue":25.4,"visits":258,"category":"18-28","guestValue":17,"visits":394,"category":"29+","guestValue":9.7,"visits":847];
$scope.downloadReports = function() // we can download our json data in many formats. ex: csv, excel
// var filename = "someFileName.xlsx"
var filename = "RawData.csv"
//alasql('SELECT id as ID,name as Name INTO XLSX("' + filename + '",headers:true) FROM ?', [$scope.OrganizationUsersList]);
alasql('SELECT * INTO CSV("' + filename + '",headers:true) FROM ?', [$scope.data]);
;
$scope.downloadReports_xlsx = function()
var filename = "RawData.xlsx"
// alasql('SELECT * INTO XLSML("RawData.xls",?) FROM ?',[$scope.data]);
alasql('SELECT * INTO XLSX("' + filename + '",headers:true) FROM ?', [$scope.data]);
;
);
</script>
</head>
<body ng-app="app" ng-controller="downloader">
<div style="float: left">
<button class="btn btn-xs btn-white" ng-click="downloadReports()">Download CSV Report</button>
<button class="btn btn-xs btn-white" ng-click="downloadReports_xlsx()">Download Excel Report</button>
<p id="heading">CSV to JSON Converter</p>
<p class="small"><a href="http://jsfiddle.net/sturtevant/vUnF9/" target="_blank">JSON to CSV Converter</a>
<hr />
<p>Paste Your CSV Here:</p>
<textarea id="csv" class="text">"Id","UserName"
"1","Sam Smith"
"2","Fred Frankly"
"1","Zachary Zupers"</textarea>
<br />
<button id="convert">Convert to JSON</button>
<button id="download">Download JSON</button>
<textarea id="json" class="text"></textarea>
<p>Based on code posted <a href="http://www.bennadel.com/blog/1504-Ask-Ben-Parsing-CSV-Strings-With-javascript-Exec-Regular-Expression-Command.htm" target="_blank">here on Ben Nadel's blog</a></p>
</div>
</body>
<body ng-app="app" ng-controller="downloader">
<div style="float: left">
<p id="heading">JSON to CSV Converter</p>
<p class="small"><a href="http://jsfiddle.net/sturtevant/AZFvQ/" target="_blank">CSV to JSON Converter</a>
<hr />
<p>Paste Your JSON Here:</p>
<textarea id="json" class="text">["Id":1,"UserName":"Sam Smith",
"Id":2,"UserName":"Fred Frankly",
"Id":1,"UserName":"Zachary Zupers"]</textarea>
<br />
<input id="quote" type="checkbox" checked="true" /> Wrap values in double quotes
<br />
<input id="labels" type="checkbox" checked="true" /> Include labels in first row
<br />
<button id="convert">Convert to CSV</button>
<button id="download">Download CSV</button>
<textarea id="csv" class="text"></textarea>
<p>Based on code posted <a href="http://***.com/a/4130939/317" target="_blank">here on ***</a></p>
</div>
</body>
</html>
【问题讨论】:
您的控制台是否报告任何错误? 没有任何错误。它只是没有输出正确的东西,或者什么也没有发生。我正在使用 JSFiddle 【参考方案1】:当我点击“下载 JSON”时,它会给我一个 CSV 文件
<button id="download">Download JSON</button>
...
$("#download").click(function()
var json = $.parseJSON($("#json").val());
var csv = JSON2CSV(json);
window.open("data:text/csv;charset=utf-8," + escape(csv))
);
看起来这就是你要求它做的事情......
【讨论】:
我使用的是相同的代码,但下载时不显示文件的扩展名。如何让扩展程序显示?以上是关于无法将 .json 文件从 CSV 下载到 JSON 转换并且无法将 JSON 转换为 CSV的主要内容,如果未能解决你的问题,请参考以下文章
在 Angular 应用程序中将 json 文件(从 json-server)下载为 txt 或 json 或 csv 文件