使用node.js将嵌套的json转换为csv

时间:2014-12-09 07:28:49

标签: json node.js csv

我想使用node.js将嵌套的json转换为csv文件。 我的JSON结构:

[
{
    "Make": "Nissan",
    "Model": "Murano",
    "Year": "2013",
    "Specifications": {
        "Mileage": "7106",
        "Trim": "SAWD"
    },
    "Items": [
        {
            "flavor": {
                "name": "Cherry",
                "id": 1
            },
            "packSize": {
                "name": "200ML",
                "id": 1
            }
        },
        {
            "flavor": {
                "name": "Vanilla",
                "id": 2
            },
            "packSize": {
                "name": "300ML",
                "id": 2
            }
        }
    ]
},
{
    "Make": "BMW",
    "Model": "X5",
    "Year": "2014",
    "Specifications": {
        "Mileage": "3287",
        "Trim": "M"
    },
    "Items": [
        {
            "flavor": {
                "name": "Cherry",
                "id": 1
            },
            "packSize": {
                "name": "200ML",
                "id": 1
            }
        },
        {
            "flavor": {
                "name": "Vanilla",
                "id": 2
            },
            "packSize": {
                "name": "300ML",
                "id": 2
            }
        }
    ]
}
]

我使用过'json-2-csv'模块,但它只转换简单结构而不是嵌套结构。 只转换'make','model','year'和'specification','items'不会被转换 怎么做???

2 个答案:

答案 0 :(得分:3)

您可以非常轻松地使用模块jsonexport,请查看此示例:

以下是使用您提供的json和jsonexport:的输出 enter image description here

<强>示例:

var jsonexport = require('jsonexport');

var contacts = [{
   name: 'Bob',
   lastname: 'Smith',
   family: {
       name: 'Peter',
       type: 'Father'
   }
},{
   name: 'James',
   lastname: 'David',
   family:{
       name: 'Julie',
       type: 'Mother'
   }
},{
   name: 'Robert',
   lastname: 'Miller',
   family: null,
   location: [1231,3214,4214]
},{
   name: 'David',
   lastname: 'Martin',
   nickname: 'dmartin'
}];

jsonexport(contacts,function(err, csv){
    if(err) return console.log(err);
    console.log(csv);
});

输出:

lastname;name;family.type;family.name;nickname;location
Smith;Bob;Father;Peter;;
David;James;Mother;Julie;;
Miller;Robert;;;;1231,3214,4214
Martin;David;;;dmartin;

来源:https://www.npmjs.com/package/jsonexport

答案 1 :(得分:0)

您是否总是拥有相同数量的列?  即:你有固定(或最大数量)的物品吗?

Make;Model;Year;Mileage;Trim;Item_1_flavor_name;Item_1_packSize_name;Item_2_flavor_name;Item_2_packSize_name