Closed jimthedev closed 5 years ago
Hi @jimthedev, thanks!
I can definitely see the usefulness of supporting keys nested in arrays, which it appears the current keys
option doesn't support based on my testing. Unfortunately I won't have time to look into this for a little bit (because of grad school exams coming up), but it would be a nice addition.
Just for future reference, here's what I tried with the current code:
var converter = require('json-2-csv');
var options = {
keys : ['Make', 'Model', 'Year', 'Features.name']
};
var documents = [
{
Make: 'Nissan',
Model: ' Murano ', // Note: This value has additional padding which can be trimmed
Year: '2013',
Features: [{ name: 'AC', value: 1}, {name: 'DVD', value: 2}]
}
];
var json2csvCallback = function (err, csv) {
if (err) throw err;
console.log(csv);
};
converter.json2csv(documents, json2csvCallback, options);
Cool. That looks similar to what I have been testing (which currently doesn't work). If I get to it I'll do a PR. Thanks for confirming.
As of 3.2.0, this is now supported! So for the following JSON documents, you can specify {keys: ['features.name']}
in your options and it will pull the correct values:
[
{
"name": "list",
"features": [
{
"name": "modules"
},
{
"pros": "efficiency"
},
{
"cons": ["cost", "time"]
}
]
},
{
"name": "module",
"features": [
{
"name": "testing"
}
],
"downloads": "5k/m"
}
]
However, if you want to take full advantage of the latest changes and have the most user-friendly CSV, then I'd also recommend specifying expandArrayObjects: true
in your options object. That will tell the module that it should also parse array objects so that they're a bit more readable. The generated CSV when using this option will look like this for the above pasted JSON:
features.name
modules
testing
Thanks for reporting this and for your patience!
Hi there, great lib. Was wondering if you'd ever consider allowing options.keys to be a json path string like with lodash.get? This would allow you to have keys that are deep, even nested in arrays.
An example would be having an array of objects. At the moment there is no way to specify that you're interested in the first object's mileage.