mrodrig / json-2-csv

Convert JSON to CSV *or* CSV to JSON!
https://mrodrig.github.io/json-2-csv
MIT License
421 stars 58 forks source link

Pass default parser to custom parse value function #218

Closed Chris-James closed 2 years ago

Chris-James commented 2 years ago

Background Information

I have...

Hi @mrodrig, I'm experimenting with using json-2-csv in a project I'm working on and have a use case where I'd like to custom parse some field values but use default parsing for the others. It seems that custom parsing is currently all or nothing, that is, if you provide a parseValue function it has to handle all field values. I thought the least disruptive way to enable custom parsing on a value-by-value basis would be to provide access to the built-in parser within the custom parser function so that's what I've done with this PR. The intention is to enable "ejecting" from custom parsing by returning the result of the default parser. For example,

parseValue: (value, defaultParser) => Array.isArray(value) ? 'They do move in herds.' : defaultParser(value)

I considered supplying custom parsers for individual fields as part of the keys array (and liked that idea) but felt that this was, again, a less disruptive step in that direction. Happy to hear your feedback/thoughts/suggestions. Thanks for your work on json-2-csv.

coveralls commented 2 years ago

Coverage Status

Coverage remained the same at 98.039% when pulling a87301b5c94a76057e40bdb70b25c1852c84f106 on Chris-James:pass-default-parser-to-parse-value into 0035b4976fa80934b6aacc042a164b5a506b1468 on mrodrig:stable.

mrodrig commented 2 years ago

Hi @Chris-James, thanks for the PR! I really like this idea. I think it makes perfect sense to provide the default parser as an argument to the function and honestly am wondering why I hadn't thought of this earlier. 🙂 I can definitely see a need for custom parsers for specific keys, but I think that's something that can be added in a future release, especially since this will unblock your use case. It might also be possible to achieve that key-based parser functionality in a similar manner to the approach as here, where the key name is passed as an argument. It would take some additional changes to achieve and I don't see any reason why that would need to hold this up, so I'll plan to look into that for a future release. I'll get this merged in and released out to NPM in 3.17.0 shortly. Thanks again for the PR and sorry it took me a couple of days to get back to you!