I have a txt file, which has the following structure
Title: Blazing Saddles
Release Year: 1974
Format: VHS
Stars: Mel Brooks, Clevon Little, Harvey Korman, Gene Wilder, Slim Pickens, Madeline Kahn
Title: Casablanca
Release Year: 1942
Format: DVD
Stars: Humphrey Bogart, Ingrid Bergman, Claude Rains, Peter Lorre
Title: Charade
Release Year: 1953
Format: DVD
Stars: Audrey Hepburn, Cary Grant, Walter Matthau, James Coburn, George Kennedy
Title: Cool Hand Luke
Release Year: 1967
Format: VHS
Stars: Paul Newman, George Kennedy, Strother Martin
I already have file data in string format.
Somehow I must convert it to JSON
I’ve to try split in this way
file.buffer.toString().split('n')
But how should I move on?
2
Answers
Split on the newline character, split each of those strings by the colon symbol. Use
reduce
and create a new object in the accumulatora
when there is a blank line, otherwise set properties in the most recent object in the accumulator for every non-empty [key,value] pair encountered.You can use this npm library.
https://www.npmjs.com/package/export-from-json
Also we can get other formats csv, txt, xls etc.
You can check my usage example: https://github.com/devStack03/node-csv-json-export