我有一个链接可以在broswer中打开json数据但不幸的是我不知道如何阅读它。有没有办法使用javascript逗号分隔(csv)格式转换此数据,并将其保存在javascript变量中。我刚开始学习并且对json一无所知,如果有人可以为它编写脚本,那就太好了。
数据似乎如下:
{
"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>
但它似乎不起作用。有人可以帮忙吗?
答案 0 :(得分:93)
将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
console.log(csv.join('\r\n'))
输出:
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"
使用这种密度较小的语法以及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])
let csv = items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
console.log(csv)
答案 1 :(得分:46)
好的,我终于让这段代码工作了:
<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>
非常感谢所有贡献者的支持。
Praney
答案 2 :(得分:16)
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 = 'UserExport.csv';
$("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
$('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
答案 3 :(得分:8)
我只想在将来为人们添加一些代码,因为我试图将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(','));
答案 4 :(得分:7)
有多种选择可用于重用现有的基于标准的强大库。
如果您碰巧在项目中使用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。
答案 5 :(得分:4)
<!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>
答案 6 :(得分:2)
从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://stackoverflow.com/a/10805198/4508758
}
答案 7 :(得分:1)
如果有人也想下载它。
这是一个很棒的小功能,它将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)
答案 8 :(得分:1)
这是将对象数组转换为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')
答案 9 :(得分:1)
尝试以下示例:
示例1:
JsonArray = [{
"AccountNumber": "1234",
"AccountName": "abc",
"port": "All",
"source": "sg-a78c04f8"
}, {
"Account Number": "1234",
"Account Name": "abc",
"port": 22,
"source": "0.0.0.0/0",
}]
JsonFields = ["Account Number","Account Name","port","source"]
function JsonToCSV(){
var csvStr = fields.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;
}
Example2:
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 = fields.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();
}
答案 10 :(得分:1)
有时对象的长度不同。因此,我遇到了与凯尔·佩内尔(Kyle Pennell)相同的问题。但是,我们不对数组进行排序,而只是遍历数组并选择最长的数组。与最初排序时的O(n log(n))相比,时间复杂度降低为O(n)。
我从Christian Landgren的更新的 ES6(2016)版本中的代码开始。
["1", "2", "3", ".", "4"]
答案 11 :(得分:0)
一个简单的函数将嵌套的 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))
答案 12 :(得分:0)
这是使用优化良好且漂亮的 csv 插件的最新答案: (这里的代码可能无法在 stackoverflow 上运行,但可以在您的项目中运行,因为我已经亲自测试过)
使用 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>
答案 13 :(得分:0)
我想轻描淡写@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)
}
答案 14 :(得分:0)
我个人将使用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
库中导入特定功能
答案 15 :(得分:0)
有趣的事情没有完成或在这里工作(IE或node.js)。回答类似的问题,即有点结构化的JSON(假设无需再次复制),还包括演示代码段。 JSON To CSV conversion (JavaScript) : How to properly format CSV conversion 希望不仅单个类型转换器,而且在我的Github(在配置文件中提到)上都类似于用于分析未知JSON结构的类。 我是此答案中的代码作者以及我Github上的所有代码的作者(某些项目以fork / + translation启动)。
答案 16 :(得分:0)
对于更新的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 :(得分:-1)
写Csv。
header("Location: http://www.mypage.com/game.php");