问题描述
我正在尝试将 JavaScript 对象集转换为 CSV 格式
I am trying to convert a JavaScript object set in to CSV format
你可以了解我的 Javascript 对象,如果你把它放在在线 JSON 解析器中 https://jsonformatter.org/json 解析器
You can get the idea about my Javascript object, if you put it in online JSON parser https://jsonformatter.org/json-parser
这就是我试图解决它的方式......但它失败了...... http://jsfiddle.net/fHQzC/11/
This is how I tried to work it out... but it flopped.. http://jsfiddle.net/fHQzC/11/
我正在尝试获取与值term"相对应的整个值.和相应的 CSV 格式的标题
I am trying to take the whole values corresponding to the value "term" and corresponding title in to CSV format
预期输出类似于
Time,Dec 9, 2012
News,Germany,election, Egypt,Revolution, Japan, Earthquake
Person,Obama, Beckham
Title,Pearce Snubs Beckham
Time,Dec 5, Birthday
Person, Lebron James
News,Italy,Euro 2012 Final
Title-Heats National Champions
是否可以在 Excel 表格中下载 csv 文件,我在 Stackoverflow 中找到的那个文件对我来说并不是真的有用...
and is it possible to download the csv file in excel sheet the one I found in Stackoverflow was not really useful me...
推荐答案
你可以试试
$(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));
});
和一个函数 ConvertToCSV
and a function ConvertToCSV
// 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;
}
这篇关于在 JavaScript 中将 JSON 对象转换为 CSV 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!