如何将 JSON 转换为 CSV 格式并存储在变量中
Posted
技术标签:
【中文标题】如何将 JSON 转换为 CSV 格式并存储在变量中【英文标题】:How to convert JSON to CSV format and store in a variable 【发布时间】:2012-02-09 11:46:54 【问题描述】:我有一个在浏览器中打开 JSON 数据的链接,但不幸的是我不知道如何阅读它。有没有办法使用 CSV 格式的 javascript 转换这些数据并将其保存在 JavaScript 文件中?
数据如下:
"count": 2,
"items": [
"title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
"description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China\u2019s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store\u2019s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
"link": "http:\/\/wik.io\/info\/US\/309201303",
"timestamp": 1326439500,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http:\/\/wikio.com\/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "2388575404943858468"
,
"title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
"description": "SHANGHAI \u2013 Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
"link": "http:\/\/wik.io\/info\/US\/309198933",
"timestamp": 1326439320,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http:\/\/wikio.com\/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "16209851193593872066"
]
我能找到的最接近的是:Convert JSON format to CSV format for MS Excel
但它以 CSV 文件的形式下载,我将其存储在一个变量中,即整个转换后的数据。
也想知道如何将转义字符:'\u2019'
恢复正常。
我试过这段代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSON to CSV</title>
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
var json3 =
"count": 2,
"items": [
"title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
"description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
"link": "http://wik.io/info/US/309201303",
"timestamp": 1326439500,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http://wikio.com/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "2388575404943858468"
,
"title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
"description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
"link": "http://wik.io/info/US/309198933",
"timestamp": 1326439320,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http://wikio.com/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "16209851193593872066"
]
//var objJson = JSON.parse(json3.items);
DownloadJSON2CSV(json3.items);
function DownloadJSON2CSV(objArray)
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])
line += array[i][index] + ',';
line.slice(0, line.Length - 1);
str += line + '\r\n';
$('div').html(str);
</script>
</head>
<body>
<div></div>
</body>
</html>
但它似乎不起作用。有人可以帮忙吗?
【问题讨论】:
zachhunter.com/2011/06/json-to-csv 呢? 你有一个很好的代码。下载的行是 window.open("data:text/csv;charset=utf-8," + escape(str)).. 如果你不需要它就跳过它。并且 csv 字符串保存在这个变量中:str CSV 不能像 JSON 一样处理多级数据(以及)。你希望你的 JSON 看起来像 CSV 吗?2,Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust), ...
?
我希望我的数据看起来像这样:Apple iPhone 4S 在北京的销售在混乱中被取消(Design You Trust),在此与 BSA 一起做广告 Apple 取消了其在其中一家商店的 iPhone 4S 预定销售。 .,,,,,, 等等 我可以很容易地删除这个起始字符:" "count":2,"items":[:"
@zdrsh 是的,但由于某种原因我无法让它工作。
【参考方案1】:
我发现例外答案非常有用,但需要我的解决方案来处理非结构化 json 对象。
我已经修改了接受的答案,以处理一系列不同大小和架构的非结构化对象。
输入:
[
"name": "Item 1",
"color": "Green",
"sizerange":
"max": "X-Large",
"min": "X-Small"
,
"name": "Item 2",
"color": "Green",
"size": "X-Large",
"owner":
"name": "Bill",
"address":
"line1": "1 test st",
"suburb": "testville"
,
"name": "Item 3",
"color": "Green",
"sizes": [
"X-Large",
"Large",
"Small"
]
]
输出:
"name","color","sizerange.max","sizerange.min","size","owner.name","owner.address.line1","owner.address.suburb","sizes.0","sizes.1","sizes.2"
"Item 1","Green","X-Large","X-Small","","","","","","",""
"Item 2","Green","","","X-Large","Bill","1 test st","testville","","",""
"Item 3","Green","","","","","","","X-Large","Large","Small"
// JSON to CSV Converter
//https://www.codegrepper.com/code-examples/javascript/javascript+array+to+csv+string
function objectToCSVRow(dataObject)
var dataArray = [];
for (var o in dataObject)
var innerValue = typeof dataObject[o] == 'undefined' ? '' : dataObject[o].toString();
var result = innerValue.replace(/"/g, '""');
result = '"' + result + '"';
dataArray.push(result);
return dataArray.join(',') + '\r\n';
//https://***.com/a/6491621
function findbystring(o, s)
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i)
var k = a[i];
if (k in o)
o = o[k];
else
return;
return o;
function pushUnique(arr, item)
if (item != "" && !arr.includes(item))
arr.push(item);
function getLabels(name, item, labels)
if (typeof item == 'object')
for (var index in item)
thisname = ""
if (name != "") thisname = name + ".";
thisname += index;
getLabels(thisname, item[index], labels);
else
pushUnique(labels, name);
function ConvertToCSV(objArray)
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
var labels = [];
for (var i = 0; i < array.length; i++)
getLabels("", array[i], labels);
str += objectToCSVRow(labels);
for (var i = 0; i < array.length; i++)
var line = [];
for (var label in labels)
line.push(findbystring(array[i], labels[label]));
str += objectToCSVRow(line);
return str;
// Example
$(document).ready(function()
// Create Object
var items = [
name: "Item 1",
color: "Green",
sizerange:
max: "X-Large",
min: "X-Small"
,
name: "Item 2",
color: "Green",
size: "X-Large",
owner:
name: "Bill",
address:
line1: "1 test st",
suburb: "testville"
,
name: "Item 3",
color: "Green",
sizes: ["X-Large", "Large", "Small"]
];
// Convert Object to JSON
var jsonObject = JSON.stringify(items, null, 2);
// Display JSON
$('#json').text(jsonObject);
// Convert JSON to CSV & Display CSV
$('#csv').text(ConvertToCSV(jsonObject));
);
<html>
<head>
<title>Demo - Covnert JSON to CSV</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<h1>
JSON</h1>
<pre id="json"></pre>
<h1>
CSV</h1>
<pre id="csv"></pre>
</body>
</html>
【讨论】:
【参考方案2】:将对象数组转换为 CSV 的优雅方法:
const convertToCsv = (arr) =>
const keys = Object.keys(arr[0]);
const replacer = (_key, value) => value === null ? '' : value;
const processRow = row => keys.map(key => JSON.stringify(row[key], replacer)).join(',');
return [ keys.join(','), ...arr.map(processRow) ].join('\r\n');
;
将其下载为文件:
const downloadFile = (fileName, data) =>
var link = document.createElement('a');
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
link.setAttribute('download', fileName);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
;
【讨论】:
【参考方案3】:这是我的解决方案,因为这里没有其他人支持动态列(他们使用第一行来确定列):
function toCsv(summary, replacer = (_, v) => v)
let csv = [[]]
for (const data of summary)
let row = []
for (const column in data)
let columnIndex = csv[0].indexOf(column)
if (columnIndex === -1)
columnIndex = csv[0].length
csv[0].push(column)
row[columnIndex] = replacer(column, data[column])
csv.push(row.join(","))
csv[0] = csv[0].join(",")
return csv.join("\r\n")
如果您需要转换某些列的值,可以传递replacer
函数。
【讨论】:
【参考方案4】:一个简单的函数将嵌套的 JS 对象(没有数组)以内联和格式化样式转换为 csv 格式..
const Obj2Csv = (data, level = 0) => (
Object.keys(data).reduce((prevValue, currValue) =>
if (typeof data[currValue] === 'object' && !Array.isArray(data[currValue]))
// format a deeper object
const formattedObjProp = `$prevValue$','.repeat(level)$currValue\r\n`;
level++;
const formattedObj = `$formattedObjProp$Obj2Csv(data[currValue], level)`;
level--;
return formattedObj;
return `$prevValue$','.repeat(level)$currValue,$data[currValue]\r\n`
, '')
)
const obj =
baz:
foo:
bar: 5
;
console.log(Obj2Csv(obj))
【讨论】:
【参考方案5】:这是使用优化良好且漂亮的 csv 插件的最新答案: (代码可能无法在此处的 *** 上运行,但可以在您的项目中运行,因为我自己测试过)
使用 jquery 和 jquery.csv 库(优化得非常好,完美地避开了一切) https://github.com/typeiii/jquery-csv
// Create an array of objects
const data = [
name: "Item 1", color: "Green", size: "X-Large" ,
name: "Item 2", color: "Green", size: "X-Large" ,
name: "Item 3", color: "Green", size: "X-Large"
];
// Convert to csv
const csv = $.csv.fromObjects(data);
// Download file as csv function
const downloadBlobAsFile = function(csv, filename)
var downloadLink = document.createElement("a");
var blob = new Blob([csv], type: 'text/csv' );
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = filename;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
// Download csv file
downloadBlobAsFile(csv, 'filename.csv');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.tutorialjinni.com/jquery-csv/1.0.11/jquery.csv.min.js"></script>
【讨论】:
【参考方案6】:praneybehl 提供的非常好的解决方案,但如果有人想将数据保存为 csv
文件并使用 blob
方法,那么他们可以参考:
function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel)
//If JSONData is not an object then JSON.parse will parse the JSON string in an Object
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
//This condition will generate the Label/Header
if (ShowLabel)
var row = "";
//This loop will extract the label from 1st index of on array
for (var index in arrData[0])
//Now convert each value to string and comma-seprated
row += index + ',';
row = row.slice(0, -1);
//append Label row with line break
CSV += row + '\r\n';
//1st loop is to extract each row
for (var i = 0; i < arrData.length; i++)
var row = "";
//2nd loop will extract each column and convert it in string comma-seprated
for (var index in arrData[i])
row += '"' + arrData[i][index] + '",';
row.slice(0, row.length - 1);
//add a line break after each row
CSV += row + '\r\n';
if (CSV == '')
alert("Invalid data");
return;
//this trick will generate a temp "a" tag
var link = document.createElement("a");
link.id = "lnkDwnldLnk";
//this part will append the anchor tag and remove it after automatic click
document.body.appendChild(link);
var csv = CSV;
blob = new Blob([csv], type: 'text/csv' );
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = (ReportTitle || 'UserExport') + '.csv';
$("#lnkDwnldLnk")
.attr(
'download': filename,
'href': csvUrl
);
$('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
【讨论】:
这个解决方案有效,但有一些奇怪的地方——你定义了var row
两次(if 语句和 for 循环不创建闭包)。标签/标题循环也可能减少到一行:Object.keys(arrData[0]).join(',')
您的回答有效。但是对于某些情况,如果某些列对某些行不可用,它不会考虑丢失的列,也不会重新对齐该行数据的列数据。
我能够让这个方法工作,但我不得不编辑一些代码:1. 不使用 JQuery 工作:document.getElementById("lnkDwnldLnk").download = filename;
document.getElementById("lnkDwnldLnk").href = csvUrl;
2. 在 IE11 中工作:if (window.navigator && window.navigator.msSaveOrOpenBlob)
@ 987654329@ else
document.getElementById('lnkDwnldLnk').click();
【参考方案7】:
将 json 转换为 csv 的更优雅的方法是使用 map 函数,无需任何框架:
var json = json3.items
var fields = Object.keys(json[0])
var replacer = function(key, value) return value === null ? '' : value
var csv = json.map(function(row)
return fields.map(function(fieldName)
return JSON.stringify(row[fieldName], replacer)
).join(',')
)
csv.unshift(fields.join(',')) // add header column
csv = csv.join('\r\n');
console.log(csv)
输出:
title,description,link,timestamp,image,embed,language,user,user_image,user_link,user_id,geo,source,favicon,type,domain,id
"Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)","Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309201303","1326439500","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","2388575404943858468"
"Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)","SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309198933","1326439320","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","16209851193593872066"
更新 ES6 (2016)
使用这种不太密集的语法和 JSON.stringify 来为字符串添加引号,同时保持数字不被引用:
const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
const csv = [
header.join(','), // header row first
...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')
console.log(csv)
【讨论】:
我喜欢它的简洁性,但应该注意的是它不能处理一些可能有些人认为理想的事情。例如每条记录单独一行,数字和布尔值不加引号,等等。 您可以在 fields.map() 之后添加一个 + "\r\n" 以获取每行一条记录。要获取不带引号的数字,您可以使用 JSON.stringify(row[fieldName]) 代替,它只会引用字符串并保留不带引号的数字。 @sunliffe :我用 JSON.stringify 更新了一个新示例 - 它应该可以处理您描述的情况。 @marathon,很好,用替换器更新了示例,以分别处理空情况。如果不使用替换器,则 null 将输出为null
- 现在示例应该正确处理 null、未定义和数字。
值得注意的是,这使用 \"
转义引号中的字符串,这允许在 Excel 中查看时某些字段“弹出”其列(这似乎更喜欢 ""
作为引号的转义字符)。这可以通过将.replace(/\\"/g, '""')
添加到JSON.stringify(row[fieldName], replacer)
的末尾来解决,正如我在上面的回答中所指出的那样。【参考方案8】:
试试这些例子
示例 1:
JsonArray = [
"AccountNumber": "123",
"AccountName": "abc",
"port": "All",
"source": "sg-a78c04f8"
,
"Account Number": "123",
"Account Name": "abc",
"port": 22,
"source": "0.0.0.0/0",
]
JsonFields = ["Account Number","Account Name","port","source"]
function JsonToCSV()
var csvStr = JsonFields.join(",") + "\n";
JsonArray.forEach(element =>
AccountNumber = element.AccountNumber;
AccountName = element.AccountName;
port = element.port
source = element.source
csvStr += AccountNumber + ',' + AccountName + ',' + port + ',' + source + "\n";
)
return csvStr;
示例2:
JsonArray = [
"AccountNumber": "1234",
"AccountName": "abc",
"inbound": [
"port": "All",
"source": "sg-a78c04f8"
,
"port": 22,
"source": "0.0.0.0/0",
]
]
JsonFields = ["Account Number", "Account Name", "port", "source"]
function JsonToCSV()
var csvStr = JsonFields.join(",") + "\n";
JsonArray.forEach(element =>
AccountNumber = element.AccountNumber;
AccountName = element.AccountName;
element.inbound.forEach(inboundELe =>
port = inboundELe.port
source = inboundELe.source
csvStr += AccountNumber + ',' + AccountName + ',' + port + ',' + source + "\n";
)
)
return csvStr;
您甚至可以使用以下代码下载 csv 文件:
function downloadCSV(csvStr)
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csvStr);
hiddenElement.target = '_blank';
hiddenElement.download = 'output.csv';
hiddenElement.click();
【讨论】:
【参考方案9】:这是我将对象数组转换为 CSV 的简单版本(假设这些对象都共享相同的属性):
var csv = []
if (items.length)
var keys = Object.keys(items[0])
csv.push(keys.join(','))
items.forEach(item =>
let vals = keys.map(key => item[key] || '')
csv.push(vals.join(','))
)
csv = csv.join('\n')
【讨论】:
【参考方案10】:改编自 praneybehl answer 以使用嵌套对象和制表符分隔符
function ConvertToCSV(objArray)
let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
if(!Array.isArray(array))
array = [array];
let str = '';
for (let i = 0; i < array.length; i++)
let line = '';
for (let index in array[i])
if (line != '') line += ','
const item = array[i][index];
line += (typeof item === 'object' && item !== null ? ConvertToCSV(item) : item);
str += line + '\r\n';
do
str = str.replace(',','\t').replace('\t\t', '\t');
while(str.includes(',') || str.includes('\t\t'));
return str.replace(/(\r\n|\n|\r)/gm, ""); //removing line breaks: https://***.com/a/10805198/4508758
【讨论】:
这非常适合直接复制和粘贴到 Excel/Sheets 中!谢谢!【参考方案11】:我想重复上面@Christian Landgren 的回答。我很困惑为什么我的 CSV 文件只有 3 列/标题。这是因为我的 json 中的第一个元素只有 3 个键。所以你需要小心const header = Object.keys(json[0])
行。假设数组中的第一个元素具有代表性。我有凌乱的 JSON,有些对象或多或少。
所以我在其中添加了一个array.sort
,它将按键数对 JSON 进行排序。这样您的 CSV 文件将具有最大列数。
这也是您可以在代码中使用的函数。只需输入 JSON!
function convertJSONtocsv(json)
if (json.length === 0)
return;
json.sort(function(a,b)
return Object.keys(b).length - Object.keys(a).length;
);
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(json[0])
let csv = json.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
fs.writeFileSync('awesome.csv', csv)
【讨论】:
【参考方案12】:有时对象有不同的长度。所以我遇到了和 Kyle Pennell 一样的问题。但是我们不是对数组进行排序,而是简单地遍历它并选择最长的。与第一次排序时的 O(n log(n)) 相比,时间复杂度降低到 O(n)。
我从 Christian Landgren 更新的 ES6 (2016) 版本的代码开始。
json2csv(json)
// you can skip this step if your input is a proper array anyways:
const simpleArray = JSON.parse(json)
// in array look for the object with most keys to use as header
const header = simpleArray.map((x) => Object.keys(x))
.reduce((acc, cur) => (acc.length > cur.length ? acc : cur), []);
// specify how you want to handle null values here
const replacer = (key, value) => (
value === undefined || value === null ? '' : value);
let csv = simpleArray.map((row) => header.map(
(fieldName) => JSON.stringify(row[fieldName], replacer)).join(','));
csv = [header.join(','), ...csv];
return csv.join('\r\n');
【讨论】:
【参考方案13】:我个人会使用d3-dsv 库来执行此操作。为什么要reinvent the wheel
?
import csvFormat from 'd3-dsv';
/**
* Based on input data convert it to csv formatted string
* @param (Array) columnsToBeIncluded array of column names (strings)
* which needs to be included in the formated csv
* @param Array input array of object which need to be transformed to string
*/
export function convertDataToCSVFormatString(input, columnsToBeIncluded = [])
if (columnsToBeIncluded.length === 0)
return csvFormat(input);
return csvFormat(input, columnsToBeIncluded);
使用tree-shaking,您只需从d3-dsv
库中导入该特定函数
【讨论】:
【参考方案14】:有趣的是,这里没有完成也没有工作(IE 和 node.js)。回答类似的问题,有点结构化的 JSON(假设不需要再次复制),还包括演示 sn-p。 JSON To CSV conversion (JavaScript) : How to properly format CSV conversion 希望不仅是单一类型的转换器,在我的 Github(在配置文件中提到)也类似用于分析未知的 JSON 结构。 我是这个答案的代码作者以及我的 Github 上的所有代码(除了一些以 fork/+translation 开头的项目)。
【讨论】:
【参考方案15】:如果有人也想下载它。 这是一个很棒的小函数,可以将 JSON 对象数组转换为 csv,然后下载。
downloadCSVFromJson = (filename, arrayOfJson) =>
// convert JSON to CSV
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(arrayOfJson[0])
let csv = arrayOfJson.map(row => header.map(fieldName =>
JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
// Create link and download
var link = document.createElement('a');
link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(csv));
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
;
然后这样称呼它:
this.downloadCSVFromJson(`myCustomName.csv`, this.state.csvArrayOfJson)
【讨论】:
当其中一个元素中有单引号时,这似乎不起作用,例如Cap D'antibes
【参考方案16】:
对于较新的 js 版本,这是一种以面向对象的方式动态处理深层对象的方法。您可能需要在区域之后更改分隔符类型。
private ConvertToCSV(objArray)
let rows = typeof objArray !== "object" ? JSON.parse(objArray) : objArray;
let header = "";
Object.keys(rows[0]).map(pr => (header += pr + ";"));
let str = "";
rows.forEach(row =>
let line = "";
let columns =
typeof row !== "object" ? JSON.parse(row) : Object.values(row);
columns.forEach(column =>
if (line !== "")
line += ";";
if (typeof column === "object")
line += JSON.stringify(column);
else
line += column;
);
str += line + "\r\n";
);
return header + "\r\n" + str;
【讨论】:
【参考方案17】:我只是想在这里为将来的人们添加一些代码,因为我试图将 JSON 导出为 CSV 文档并下载它。
我使用$.getJSON
从外部页面提取json数据,但如果你有一个基本数组,你可以直接使用它。
这使用 Christian Landgren 的代码来创建 csv 数据。
$(document).ready(function()
var JSONData = $.getJSON("GetJsonData.php", function(data)
var items = data;
const replacer = (key, value) => value === null ? '' : value; // specify how you want to handle null values here
const header = Object.keys(items[0]);
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
csv.unshift(header.join(','));
csv = csv.join('\r\n');
//Download the file as CSV
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csv]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "DataDump.csv"; //Name the file here
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
);
);
编辑:值得注意的是,JSON.stringify
将通过添加 \"
来转义引号中的引号。如果您在 excel 中查看 CSV,它不喜欢将其作为转义字符。
您可以将.replace(/\\"/g, '""')
添加到JSON.stringify(row[fieldName], replacer)
的末尾以在excel 中正确显示(这会将\"
替换为""
,这是excel 喜欢的)。
全线:let csv = items.map(row => header.map(fieldName => (JSON.stringify(row[fieldName], replacer).replace(/\\"/g, '""'))).join(','));
【讨论】:
可能只是我,但我得到了TypeError: Cannot read property 'replace' of undefined
@KylePennell 没错,我也明白了,我真的需要他的修复。
如果JSON.stringify
正在返回undefined
,那么您可能有更大的问题?如果没有.replace
行,您会返回数据吗?【参考方案18】:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JSON to CSV</title>
<script src="http://code.jquery.com/jquery-1.7.1.js" type="text/javascript"></script>
</head>
<body>
<h1>This page does nothing....</h1>
<script type="text/javascript">
var json3 =
"count": 2,
"items": [
"title": "Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)",
"description": "Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone",
"link": "http://wik.io/info/US/309201303",
"timestamp": 1326439500,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http://wikio.com/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "2388575404943858468"
,
"title": "Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)",
"description": "SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone",
"link": "http://wik.io/info/US/309198933",
"timestamp": 1326439320,
"image": null,
"embed": null,
"language": null,
"user": null,
"user_image": null,
"user_link": null,
"user_id": null,
"geo": null,
"source": "wikio",
"favicon": "http://wikio.com/favicon.ico",
"type": "blogs",
"domain": "wik.io",
"id": "16209851193593872066"
]
;
const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
var link = document.createElement("a");
link.id="lnkDwnldLnk";
document.body.appendChild(link);
blob = new Blob([csv], type: 'text/csv' );
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = 'UserExport.csv';
jQuery("#lnkDwnldLnk")
.attr(
'download': filename,
'href': csvUrl
);
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
</script>
</body>
</html>
【讨论】:
【参考方案19】:有多种选项可用于重用基于标准的现有强大库。
如果你碰巧在你的项目中使用了 D3,那么你可以简单地调用:
d3.csv.format
或 d3.csv.formatRows
函数将对象数组转换为 csv 字符串。
d3.csv.formatRows
让您可以更好地控制将哪些属性转换为 csv。
请参阅 d3.csv.format 和 d3.csv.formatRows 维基页面。
还有其他可用的库,例如 jquery-csv、PapaParse。 Papa Parse 没有依赖项——甚至 jQuery 也没有。
对于基于 jquery 的插件,请check this。
【讨论】:
这对我很有用。请注意,自 2017.v3(当前为 v4)以来,D3 API 发生了变化:github.com/d3/d3-dsv/blob/v1.2.0/README.md#csvFormat 谢谢!我使用了 PapaParse 的 Papa.unparse(data) (papaparse.com/docs#json-to-csv)。快速解决我的问题!【参考方案20】:编写 CSV。
function writeToCsv(dataToWrite, callback)
var dataToWrite;
var fs = require('fs');
dataToWrite = convertToCSV(dataToWrite);
fs.writeFile('assets/distanceInfo.csv', dataToWrite, 'utf8', function (err)
if (err)
console.log('Some error occured - file either not saved or corrupted file saved.');
else
console.log('It\'s saved!');
callback("data_saved | assets/distanceInfo.csv")
);
function convertToCSV(objArray)
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;
【讨论】:
我认为这没什么价值。请edit添加一些解释,说明这如何有助于回答问题。【参考方案21】:好的,我终于让这段代码工作了:
<html>
<head>
<title>Demo - Covnert JSON to CSV</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<script type="text/javascript">
// JSON to CSV Converter
function ConvertToCSV(objArray)
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;
// Example
$(document).ready(function ()
// Create Object
var items = [
name: "Item 1", color: "Green", size: "X-Large" ,
name: "Item 2", color: "Green", size: "X-Large" ,
name: "Item 3", color: "Green", size: "X-Large" ];
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
// Display JSON
$('#json').text(jsonObject);
// Convert JSON to CSV & Display CSV
$('#csv').text(ConvertToCSV(jsonObject));
);
</script>
</head>
<body>
<h1>
JSON</h1>
<pre id="json"></pre>
<h1>
CSV</h1>
<pre id="csv"></pre>
</body>
</html>
非常感谢所有贡献者的支持。
普拉尼
【讨论】:
我试过这个。我有三列,但在 excel 中,所有内容都将集中在一个列中 Nithesh 你应该指定 ',' 作为分隔符 感谢您在这里分享。刚刚用过,效果很好。 谢谢!如果单元格包含对象,我添加了以下内容以避免在行中出现“[object Object]”。 if (_.isObject(array[i][index])) array[i][index] = JSON.stringify(array[i][index]); 。 (使用下划线,但你可以改为原版) @Sunil 我发现如果值包含逗号,它会中断。为了我的需要,我只是这样做了: var re = new RegExp(',', 'g'); array[i][index] = array[i][index].toString().replace(re, ';')以上是关于如何将 JSON 转换为 CSV 格式并存储在变量中的主要内容,如果未能解决你的问题,请参考以下文章
如何将 csv 转换为 json 并编写特定函数以使用 javascript 生成图形?
如何将 Json 转换为 CSV 并将其发送到大查询或谷歌云存储桶