英文:
Data not completely convert from JSON to CSV
问题
以下是翻译好的部分:
我有一组如下所示的JSON格式。在从JSON转换为CSV时,函数可以工作,但并不是所有的“key”都存在于CSV文件中。如何使CSV文件中的所有“key”都可用?
JSON
var data = {
"items": [
{
"bandwidth": "",
"destination_ipv4": "",
"destination_ipv6": ""
},
{
"interface": "",
"alarm": false,
"service": [
]
},
{
"unit": {
"name": "operation",
"shaping-rate": {
"rate": "1G"
}
},
"ipv6_address": ""
},
{
"vrf": ""
}
]
};
当前结果
期望结果
JS
function download_file(data) {
const items = data.items;
const replacer = (key, value) => value === null ? '' : value;
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 = 'Result.csv';
jQuery("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
请注意,图片描述和链接无法提供翻译。
英文:
I have a set of JSON format as below. During converting from JSON to CSV, the function is worked but not all key
is exist in the CSV file. How to allow all the key
available in the CSV file?
Reference: How to convert JSON to CSV format and store in a variable
JSON
var data={
"items": [
{
"bandwidth": "",
"destination_ipv4": "",
"destination_ipv6": ""
},
{
"interface": "",
"alarm": false,
"service": [
]
},
{
"unit": {
"name": "operation",
"shaping-rate": {
"rate": "1G"
}
},
"ipv6_address": ""
},
{
"vrf": ""
}
]
};
JS
function download_file(data) {
const items = data.items
const replacer = (key, value) => value === null ? '' : value
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 = 'Result.csv';
jQuery("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
答案1
得分: 2
不要翻译代码部分,以下是翻译好的内容:
"Instead of just using the first element in data.items
you will need to get all keys from all elements in the array.
You can do this using Array.prototype.flatMap
You should use this instead of const header = Object.keys(items[0]);
"
英文:
Instead of just using the first element in data.items
you will need to get all keys from all elements in the array.
You can do this using Array.prototype.flatMap
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const data = {
"items": [{
"bandwidth": "",
"destination_ipv4": "",
"destination_ipv6": ""
},
{
"interface": "",
"vlan": null,
"service": ""
},
{
"ipv4_address": "",
"ipv6_address": ""
},
{
"vrf": ""
}
]
};
const items = data.items;
const header = items.flatMap(item => Object.keys(item));
console.log(header);
<!-- end snippet -->
You should use this instead of const header = Object.keys(items[0]);
答案2
得分: 2
这是我的版本
var data = { "items": [{ "bandwidth": "A", "destination_ipv4": "B", "destination_ipv6": "C" }, { "interface": "D", "vlan": null, "service": "E" }, { "ipv4_address": "F", "ipv6_address": "G" }, { "vrf": "H" }] };
const items = data.items;
let rows = [];
const header = items.map(item => {
rows = rows.concat(Object.values(item));
return Object.keys(item);
})
.flat()
.join(",");
const csv = [header, rows.join(",")].join("\n");
console.log(csv)
请注意,我只对代码进行了翻译,没有翻译注释部分。
英文:
Here is my version
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var data = { "items": [{ "bandwidth": "A", "destination_ipv4": "B", "destination_ipv6": "C" }, { "interface": "D", "vlan": null, "service": "E" }, { "ipv4_address": "F", "ipv6_address": "G" }, { "vrf": "H" } ] };
const items = data.items;
let rows = [];
const header = items.map(item => {
rows = rows.concat(Object.values(item));
return Object.keys(item);
})
.flat()
.join(",")
const csv = [header, rows.join(",")].join("\n");
console.log(csv)
<!-- end snippet -->
答案3
得分: 0
在提供的JavaScript代码中,header变量用于存储items数组中第一个对象的键。这意味着只有第一个对象的键将被用作CSV文件中的标题。要在CSV文件中包括所有对象的所有键,可以按如下修改代码:
function download_file(data) {
const items = data.items;
const replacer = (key, value) => value === null ? '' : value;
// 从items数组中的所有对象获取所有唯一键
const allKeys = items.reduce((keys, obj) => {
Object.keys(obj).forEach(key => {
if (!keys.includes(key)) keys.push(key);
});
return keys;
}, []);
const csv = items.map(row => allKeys.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
// 添加包含所有键的标题行
csv.unshift(allKeys.join(','));
const csvString = csv.join('\r\n');
var link = document.createElement("a");
link.id="lnkDwnldLnk";
document.body.appendChild(link);
blob = new Blob([csvString], { type: 'text/csv' });
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = 'Result.csv';
jQuery("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
这个修改后的代码使用reduce方法迭代items数组中的每个对象,并收集所有唯一键。然后使用这些键创建CSV文件中的标题行。
通过这个修改,CSV文件将包括items数组中所有对象的所有键。
英文:
In the provided JavaScript code, the header variable is used to store the keys of the first object in the items array. This means that only the keys of the first object will be used as the header in the CSV file. To include all the keys from all the objects in the CSV file, you can modify the code as follows:
function download_file(data) {
const items = data.items;
const replacer = (key, value) => value === null ? '' : value;
// Get all unique keys from all objects in the items array
const allKeys = items.reduce((keys, obj) => {
Object.keys(obj).forEach(key => {
if (!keys.includes(key)) keys.push(key);
});
return keys;
}, []);
const csv = items.map(row => allKeys.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','));
// Add the header row with all keys
csv.unshift(allKeys.join(','));
const csvString = csv.join('\r\n');
var link = document.createElement("a");
link.id="lnkDwnldLnk";
document.body.appendChild(link);
blob = new Blob([csvString], { type: 'text/csv' });
var csvUrl = window.webkitURL.createObjectURL(blob);
var filename = 'Result.csv';
jQuery("#lnkDwnldLnk")
.attr({
'download': filename,
'href': csvUrl
});
jQuery('#lnkDwnldLnk')[0].click();
document.body.removeChild(link);
}
This modified code uses the reduce method to iterate over each object in the items array and collect all the unique keys. It then uses these keys to create the header row in the CSV file.
With this modification, all the keys from all the objects in the items array will be included in the CSV file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论