use*_*031 11 javascript node.js node-modules
我有excel表与数据列表.
这一步工作得很好.但之后我需要格式化csv文件中的数据,如excel数据和搜索结果都必须显示在csv文件中.
在这里我无法将excel数据带入csv文件.例如"本田"是excel文件中的汽车名称,我正在阅读它并搜索另一个系统.这些结果需要在csv中显示.
请指教.
Excel输入:
Car name, Description
Honda, some description
Run Code Online (Sandbox Code Playgroud)
API响应数据:
[{
"total": 10,
"results": [{
"name": {
"val": "Honda",
"id": "0271b276",
"type": "String",
},
"attributes": [{
"val": "accord",
"type": "field1",
}, {
"val": "test123",
"type": "field3",
}],
}]
},
]
Run Code Online (Sandbox Code Playgroud)
CSV文件中的期望输出.
Car Name , Description,Total results,Make , Model
honda , Description,10 , Honda, accord
Run Code Online (Sandbox Code Playgroud)
码
const _ = require('lodash');
const xlsx = require('xlsx');
const workbook = xlsx.readFile(__dirname + '/test.xlsx');
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
for (let z in worksheet) {
if(z.toString()[0] === 'A'){
request({
url: 'http://url', //URL to hit
method: 'POST',
json: {
query: worksheet[z].v,
}
}, function(error, response, data){
if(error) {
console.log(error);
} else {
var fields = ['Make','Model','total', 'results[0].name.val','results[0].name[0].val'];
var fieldNames = ['Make','Model','Total','Name','Description'];
var opts1 = {
data: data,
fields: fields,
fieldNames: fieldNames,
};
var json2csv = require('json2csv');
var csv = json2csv(opts1);
fs.writeFile('file.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});
Run Code Online (Sandbox Code Playgroud)
我已经格式化了您的 JSON,以便我可以更好地理解它:
let data = [
{
"total": 10,
"results": [
{
"name": {
"val": "test value1",
"id": "0271b276",
"type": "String",
},
"attributes": [
{
"val": "test value2",
"type": "field1",
},
{
"val": "test description",
"type": "field2",
},
{
"val": "test123",
"type": "field3",
}
],
}
]
},
[
{
"Make": "Honda",
"Model": "Accord"
}
]
];
Run Code Online (Sandbox Code Playgroud)
这是一些奇怪的 JSON。在顶层,它是一个包含两个元素的数组。第一个元素是一个对象,第二个元素是另一个数组。
您正在寻找的值似乎是
data[1][0].Make(“Honda”) <-- 注意大写的 Mdata[1][0].Model("Accord") <-- 注意大写的 Mdata[0].total(10)data[0].results[0].name.val(“测试值1”)data[0].results[0].attributes[0].val(“测试值2”)...但我不确定。
在json2csv 的 npm 页面中,数据对象必须是 JSON 对象的数组。您必须将数据重组为 json2csv 可以理解的方式。也许您的数据对象应该如下所示:
[
{
"name": {
"val": "test name 1",
"id": "0271b276",
"type": "String"
}
"attributes": [
{
"val": "attribute 1",
"type": "String"
},
{
"val": "attribute 2",
"type": "String"
},
{
"val": "attribute 3",
"type": "String"
}
],
"make": "Honda",
"model": "Accord"
},
{
"name": {
"val": "test name 2",
"id": "22e5b24e",
"type": "String"
}
"attributes": [
{
"val": "attribute A",
"type": "String"
},
{
"val": "attribute B",
"type": "String"
},
{
"val": "attribute C",
"type": "String"
}
],
"make": "Toyota",
"model": "Corolla"
}
]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
682 次 |
| 最近记录: |